Sub topic 14
Exposing a small API with useImperativeHandle
This chapter assumes you know how useRef attaches to a DOM element, how a parent can pass a ref to a child component, and how closures capture values in function components. It builds on the previous chapter, which covered passing refs to child components.
The problem with a raw forwarded ref
When a parent passes a ref to a child, and the child attaches that ref to an <input>, the parent receives the real DOM node. It can then call anything on it: focus(), but also remove(), style.display = 'none', or value = 'oops'.
That is a wide interface for a component that only meant to offer "focus me". If the child later swaps the <input> for a custom widget, every parent that used a DOM-only method breaks.
useImperativeHandle lets the child decide what the parent's ref points to. Instead of the DOM node, the parent gets an object that the child builds. That object is the handle.
The hook's signature
useImperativeHandle(ref, createHandle, dependencies?)refis the ref the parent passed in.createHandleis a function that takes no arguments and returns the object to expose.dependenciesis an optional array, like the one foruseEffect. React recreates the handle when a dependency changes.
React calls createHandle after the component mounts and assigns the result to ref.current. When the component unmounts, React sets ref.current back to null.
A first example
This is the pattern from the spine. The child keeps a private ref to the real <input> and exposes only a focus method.
import { forwardRef, useImperativeHandle, useRef } from 'react';
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current.focus();
},
}));
return <input ref={inputRef} {...props} />;
});
export function Form() {
const fancyRef = useRef(null);
return (
<>
<FancyInput ref={fancyRef} />
<button onClick={() => fancyRef.current.focus()}>Focus</button>
</>
);
}There are two refs here, and they have different jobs:
inputRefis private toFancyInput. It holds the DOM node.refis the parent's ref. It holds the handle object.
If the parent writes fancyRef.current.remove(), it gets a TypeError, because the handle has no remove method.
React 19: ref as a prop
In React 19, function components receive ref as an ordinary prop, so forwardRef is no longer needed. forwardRef still works in React 19, but new code can drop it. The hook call stays the same.
import { useImperativeHandle, useRef } from 'react';
export function FancyInput({ ref, ...props }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current.focus();
},
}));
return <input ref={inputRef} {...props} />;
}If your project runs React 18 or earlier, use the forwardRef version. In those versions a plain function component does not receive ref in its props.
Several methods
A handle can hold more than one method. Keep each method an action the parent triggers at a moment in time: focus, clear, scroll, play, reset.
import { useImperativeHandle, useRef } from 'react';
export function TextField({ ref, label }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current.focus();
},
clear() {
inputRef.current.value = '';
inputRef.current.focus();
},
}));
return (
<label>
{label}
<input ref={inputRef} />
</label>
);
}Notice what clear hides. The parent does not know the field is uncontrolled or that clearing means setting value. If you later make the input controlled, only TextField changes.
The dependencies array
The handle is created once per mount unless you say otherwise. Without a dependency array, React recreates it after every render. With [], it is created once. With specific dependencies, it is recreated when they change.
This matters when a method reads props or state. Consider a handle that returns the current count:
import { useImperativeHandle, useState } from 'react';
export function Counter({ ref }) {
const [count, setCount] = useState(0);
useImperativeHandle(
ref,
() => ({
getCount() {
return count;
},
}),
[count]
);
return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>;
}With [count], the parent always gets the latest value. If you wrote [] here, getCount would close over the first render and return 0 forever. This is the same stale-closure bug you see in useEffect.
Rules of thumb:
- Include every prop or state value that the handle's methods read.
- Methods that only touch other refs, such as
inputRef.current, need no dependencies, because a ref object is stable and.currentis read at call time. - Leaving out the array is correct but wasteful. React reassigns
ref.currentafter every render.
When the handle is available
React sets ref.current during the commit phase, at roughly the same time it attaches DOM refs. This has three consequences:
- During the parent's first render,
fancyRef.currentisnull. - In event handlers, it is available, because they run after mount.
- In the parent's effects, it is available, because child refs are attached before parent effects run.
import { useEffect, useRef } from 'react';
import { TextField } from './TextField';
export function SignIn() {
const emailRef = useRef(null);
useEffect(() => {
emailRef.current?.focus();
}, []);
return <TextField ref={emailRef} label="Email" />;
}Reading emailRef.current in the body of SignIn, outside an effect or handler, breaks the render-purity rule from earlier in this tutorial.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot read properties of null (reading 'focus')` | The parent read the ref during render, or the child is not mounted | Read it in an event handler or effect, and use `?.` if the child can be absent |
| Ref is `null` even after mount (React 18) | The child is a plain function component that never receives `ref` | Wrap it in `forwardRef` |
| Warning about function components and refs (React 18) | Same as above | Wrap it in `forwardRef` |
| Method returns old data | Dependencies omitted or too short | Add the values the method reads, for example `[count]` |
| Method does nothing | The child's private `inputRef` is not attached to an element | Check that `ref={inputRef}` is on the rendered element |
| Parent calls a method that does not exist | The handle exposes less than the parent expects | Add the method deliberately, or change the parent |
Handle or props?
A handle is an escape hatch. Reach for it when the thing you need is an action with no sensible state representation: focus, select text, scroll into view, play a video, trigger a shake animation.
Do not use it for things that can be expressed as data. Compare these two designs for a modal:
// Imperative: avoid when state would do
modalRef.current.open();
// Declarative: preferred
<Modal isOpen={isOpen} onClose={() => setIsOpen(false)} />The imperative version hides the modal's visibility from React. The parent cannot render something different while the modal is open, and the code is harder to test and to follow. A good test: if the parent needs to display the value anywhere, it belongs in state and props, not in a handle.
Keep the handle small. Every method you add becomes part of the child's public contract, and parents will depend on it.
Edge cases
- Unmount: React sets the handle to
nullwhen the child unmounts. Parents that call methods from delayed callbacks, such as asetTimeout, should use?.. - Conditional rendering: If the child is rendered only sometimes, the parent's ref is
nullwhile it is hidden. - No ref passed: If the parent passes no
ref,refisundefined(React 19) ornull(forwardRef).useImperativeHandleaccepts both and does nothing. - Callback refs: The parent may pass a callback ref instead of a ref object. React calls it with the handle, so the same code works.
- Wrapping: If a wrapper component passes its own
refthrough to your child, the handle still reaches the outermost holder of the ref.
Exercise
A VideoPlayer component renders a <video> and uses useImperativeHandle(ref, () => ({ play() { videoRef.current.play(); } }), []). The parent also needs a pause method and a isMuted() method that returns whether a muted prop is true. Which changes do you make to the hook call, and why does the dependency array matter for the second method?
Show answer
Add pause() { videoRef.current.pause(); } and isMuted() { return muted; } to the returned object. play and pause only read videoRef, which is stable, so they need no dependencies. isMuted reads the muted prop, so the array must change from [] to [muted]. With [], isMuted would close over the first render's muted and keep returning that value after the prop changes.
Exercise
A teammate writes <Dialog ref={dialogRef} /> and calls dialogRef.current.open() to show it, then asks the dialog to report back whether it is open so the page can dim its background. What design problem does this show, and what would you change?
Show answer
Whether the dialog is open is data that the parent needs to display, so it should live in state, not behind an imperative method. Change the dialog to accept isOpen and onClose props, and keep const [isOpen, setIsOpen] = useState(false) in the parent. The same state then drives both the dialog and the background dimming.