ReactJS Hook Pattern ~UseImperativeHandle~
Source: Dev.to
useImperativeHandle allows child components to expose specific methods to their parent components through a ref. This pattern is useful when you need to call functions on a child component imperatively, such as focusing an input. useImperativeHandle doesn’t expose the entire DOM node; instead, it can expose a specific method, like focusInner.
Example
import { useRef, useImperativeHandle } from "react";
function CustomInput({ ref, ...rest }) {
const localRef = useRef();
useImperativeHandle(ref, () => ({
focusInner: () => {
localRef.current.focus();
},
}));
return ;
}
function App() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focusInner();
};
return (
Focus Input
);
}
export default App;