React useImperativeHandle Hook Cheat Sheet
What is `useImperativeHandle`?
A React Hook that lets a parent component call functions or access values inside a child ref — used with forwardRef
.
import { useImperativeHandle, forwardRef } from "react";
When to Use It
- Exposing imperative methods to parent components (e.g.,
.focus()
,.reset()
) - Customizing what a parent can access through a
ref
Basic Setup
1. Wrap the child with `forwardRef`
const MyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => (inputRef.current.value = "")
}));
return <input ref={inputRef} />;
});
2. Use in parent component
const ref = useRef();
<MyInput ref={ref} />
<button onClick={() => ref.current.focus()}>Focus Input</button>
<button onClick={() => ref.current.clear()}>Clear Input</button>
Signature
useImperativeHandle(ref, createHandle, [deps]);
| Param | Description |
|--||
| ref
| The forwarded ref
from the parent |
| createHandle
| A function that returns public API |
| [deps]
| Optional dependencies for memoization |