
what is useImperativeHandle() ?
useImperativeHandle() is a React Hook used with forwardRef() to customize the instance value (i.e. what a parent can access) when it uses a ref on a child component.
Why Use useImperativeHandle()?
Normally, when a parent passes a ref to a child, it gets direct access to the DOM node (e.g., an <input> element).
With useImperativeHandle(), you can:
- Control exactly what values or functions are exposed to the parent.
- Prevent direct DOM access.
- Expose custom functions from a child component.
Syntax
useImperativeHandle(ref, () => ({
// values/functions to expose
}), [dependencies]);
Used Together With forwardRef()
Example: Custom Focus Method
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
// Child component
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} type="text" />;
});
// Parent component
function App() {
const inputRef = useRef();
return (
<>
<CustomInput ref={inputRef} />
<button onClick={() => inputRef.current.focusInput()}>Focus</button>
</>
);
}
How It Works:
- App uses ref on <CustomInput />
- Inside CustomInput, useImperativeHandle() exposes only focusInput() method
- So App can call inputRef.current.focusInput() — but can’t access raw DOM
Benefits
Feature | Why It’s Useful |
---|---|
Controlled exposure | Hide internal logic or DOM nodes |
Encapsulation | Expose only safe/public functions to parent |
Custom API for components | Let parent call child logic like reset(),openModal(), etc. |
Rules
- Must be used with forwardRef()
- Typically used for custom input, modals, animations, etc.
- Use only when necessary — avoid overusing ref
Summary
Feature | Description |
---|---|
useImperativeHandle() | Customize what a ref on a child component exposes |
Works with | forwardRef() |
Used for | Exposing child methods like focus(), reset() |
Improves | Encapsulation and safety |
Comments
Add new comment