Published on 11 October 2020
useState
, useEffect
and useCallback
are second nature to many React developers at this point.useImperativeHandle
. Now, given that React prides itself in being very declarative, it might be quite surprising to see the i-word in there, but it is actually a really interesting case that might be the tool you need to get out of a situation where you need to modify a component from the outside or create a two-way binding and access its props from the top rather than from the bottom of the component hierarchy.useImperativeHandle
uses refs, and to paraphrase React docs on the usage of refs: you don't want to use them to "make things happen". It is also somewhat counterintuitive, given that refs are usually presented to intermediate React developers as the React equivalent of getElementById
- a way to access a DOM node and operate on it directly.useImperativeHandle
hook we can use refs to access arbitrary properties using a mutable object.innerRef
, somewhat similar to what formik has. That functionality uses React's useImperativeHandle
under the covers.useImperativeHandle(ref, () => value);
ref
from the outside, we can expect that it will have the ref.current
key set to whatever we provide as value
. That value
does not have to be an actual value, but it can actually be a callback function from inside the component.const ref = React.createRef();
const InnerText = ({ innerRef }) => {
const [text, setText] = useState('before');
useImperativeHandle(innerRef, () => ({ setText }));
return <p>{text}</p>;
}
const RefHandler = ({ innerRef }) => {
const handleClick = () => innerRef.current.setText('after');
return <button onClick={handleClick}>Handle Refs</button>;
}
const Outer = () => (
<InnerText innerRef={ref} />
<RefHandler innerRef={ref} />
);
useState
function.