useImperativeHandle
In one line
useImperativeHandle lets a child component expose specific methods to a parent via ref, hiding internal details.
In simple words
useImperativeHandle customizes what a parent sees when it accesses a child's ref. Instead of exposing the raw DOM node, you can expose specific methods.
Combine with forwardRef to pass a ref from parent to child. The child uses useImperativeHandle to define what the parent can call.
Use case: a custom input component that exposes focus() and clear() but hides its internal DOM structure. The parent calls ref.current.focus() without knowing about the underlying <input>.
This is an escape hatch — prefer declarative props when possible. Use it for focus management, scrolling, animations, and integrating with non-React libraries.
Example
import { useRef, forwardRef, useImperativeHandle } from "react";
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => { inputRef.current.value = ""; },
getValue: () => inputRef.current.value,
}));
return <input ref={inputRef} {...props} />;
});
function Parent() {
const ref = useRef();
return (
<>
<FancyInput ref={ref} />
<button onClick={() => ref.current.focus()}>Focus</button>
<button onClick={() => ref.current.clear()}>Clear</button>
</>
);
}useImperativeHandle exposes only focus(), clear(), and getValue() to the parent — the internal <input> ref is hidden.
Common confusions
Confused with: useRef
The difference: useRef creates a ref that points to a DOM element or mutable value. useImperativeHandle customizes what a forwarded ref exposes to the parent — it's about controlling the ref's API, not creating a ref.
Related terms
Related Resources
Related Lessons
- React Advanced
useImperativeHandle.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.