Sub topic 14
Exposing a small API with useImperativeHandle
This chapter assumes you can use useRef with DOM elements, pass a ref from a parent to a child component, and read basic useEffect code.
The problem with a raw DOM node
When a parent passes a ref down and the child attaches it to an <input>, the parent gets the real DOM node. It can then call focus(), but it can also call remove() or change style. The child has no way to limit this.
useImperativeHandle lets the child choose what the parent receives. Instead of the DOM node, ref.current becomes an object that you build.
The API
useImperativeHandle(ref, createHandle, dependencies)refis the ref passed in by the parent.createHandleis a function that returns the object the parent will see.dependenciesis an optional array. React rebuilds the object when a dependency changes. If you leave it out, React rebuilds the object after every render.
A worked example
This FancyInput exposes only focus and clear. In React 19 a function component receives ref as an ordinary prop. In React 18 and earlier, wrap the component in forwardRef and take ref as the second argument.
import { useImperativeHandle, useRef } from 'react';
function FancyInput({ ref, ...props }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current.focus();
},
clear() {
inputRef.current.value = '';
},
}), []);
return <input ref={inputRef} {...props} />;
}
export function Form() {
const fancyRef = useRef(null);
return (
<>
<FancyInput ref={fancyRef} placeholder="Name" />
<button onClick={() => fancyRef.current.focus()}>Focus</button>
<button onClick={() => fancyRef.current.clear()}>Clear</button>
</>
);
}The child keeps its own inputRef for the real node. The parent's fancyRef points at the small object, so fancyRef.current.remove is undefined.
How it behaves
React fills in ref.current after the component commits to the screen, the same time it fills in DOM refs. It sets the value back to null when the component unmounts. So the parent should only use the handle in event handlers or effects, never during rendering.
The handle's methods read inputRef.current when they are called, not when the handle is built. This is why an empty dependency array is safe in the example. If a method used a prop or state value directly, you would list that value in the dependencies. Otherwise the method would use a stale value.
Common mistakes
- Using the handle before mount.
fancyRef.currentisnullduring the first render. - Exposing too much. Returning the whole DOM node defeats the purpose.
- Forgetting dependencies. A handle method that reads props can run with old values.
- Reaching for a handle when state or props would work. Imperative code is harder to follow.
Exercise
Why does the example pass an empty dependency array to useImperativeHandle, and when would it need a non-empty one?
Show answer
The methods only read inputRef.current at call time, and inputRef never changes, so the handle never needs rebuilding. If a method used a prop or state value, such as a maxLength prop, that value should go in the dependency array so the handle is rebuilt when it changes.