How to Use useImperativeHandle in React: Simple Guide
In React,
useImperativeHandle lets you customize the instance value that is exposed to parent components when using ref. It is used inside a forwardRef component to control which methods or properties the parent can access on the child component.Syntax
The useImperativeHandle hook takes three arguments: a ref object, a function that returns an object with the values or methods you want to expose, and an optional dependency array to control when the object updates.
- ref: The forwarded ref from the parent.
- createHandle: A function returning an object with exposed properties or methods.
- deps: Optional array to update the handle when dependencies change.
javascript
useImperativeHandle(ref, () => ({
method1: () => {},
property1: value
}), [deps])Example
This example shows a child component exposing a focus method to its parent using useImperativeHandle. The parent can call childRef.current.focus() to focus the input inside the child.
javascript
import React, { useRef, forwardRef, useImperativeHandle } from 'react'; const CustomInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} placeholder="Type here" />; }); export default function App() { const childRef = useRef(); return ( <div> <CustomInput ref={childRef} /> <button onClick={() => childRef.current.focus()}>Focus Input</button> </div> ); }
Output
A page with an input box and a button labeled 'Focus Input'. Clicking the button sets focus inside the input box.
Common Pitfalls
- Not using
forwardRefto pass the ref to the child component will makeuseImperativeHandleineffective. - Exposing too many internal details defeats the purpose of encapsulation; only expose what the parent really needs.
- Forgetting to include dependencies in the dependency array can cause stale references.
javascript
/* Wrong: Not forwarding ref */ function Child(props) { useImperativeHandle(props.ref, () => ({ alertMessage: () => alert('Hi') })); return <div>Child</div>; } /* Right: Using forwardRef */ const ChildCorrect = forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ alertMessage: () => alert('Hi') })); return <div>Child</div>; });
Quick Reference
- Use
forwardRefto pass refs to child components. - Inside the child, use
useImperativeHandleto expose only needed methods or properties. - Keep the dependency array updated to avoid stale handles.
- Use this hook to control what the parent can do with the child component's instance.
Key Takeaways
Use useImperativeHandle inside forwardRef to customize what a parent can access via ref.
Expose only necessary methods or properties to keep components encapsulated.
Always forward the ref to the child component for useImperativeHandle to work.
Include dependencies in the hook to update the exposed handle correctly.
This hook helps control child component behavior from the parent safely.