useImperativeHandle is a specialized React hook used in combination with forwardRef to customize the instance handle that a parent component receives when using a ref on a child component.
Instead of exposing the raw DOM node to the parent, useImperativeHandle allows the child component to expose a restricted, imperative API interface (such as explicit .focus() or .reset() functions).
flowchart LR
Parent["Parent Component"] -->|"customInputRef.current.focusInput()"| Handle["Imperative Handle API"]
Handle --> Child["Child Component (Imperative Focus / Scroll)"]
import React, { useRef, forwardRef, useImperativeHandle } from 'react';
// Child Component using forwardRef + useImperativeHandle
const CustomInput = forwardRef(function CustomInput(props, ref) {
const internalInputRef = useRef(null);
// Expose ONLY specific methods to parent via ref
useImperativeHandle(ref, () => ({
focusInput: () => {
internalInputRef.current?.focus();
},
clearInput: () => {
if (internalInputRef.current) {
internalInputRef.current.value = '';
}
},
}));
return (
<input
ref={internalInputRef}
type="text"
placeholder="Custom Managed Input..."
className="styled-input"
/>
);
});
// Parent Component consuming imperative child handle
export default function ParentForm() {
const customInputRef = useRef(null);
return (
<div className="card">
<CustomInput ref={customInputRef} />
<div style={{ marginTop: '1rem', display: 'flex', gap: '0.5rem' }}>
<button onClick={() => customInputRef.current?.focusInput()}>
Focus Child Field
</button>
<button onClick={() => customInputRef.current?.clearInput()}>
Clear Child Field
</button>
</div>
</div>
);
}
forwardRef: useImperativeHandle requires the child component to be wrapped in forwardRef(Component).Create a custom Video Player component that exposes .play() and .pause() methods to a parent control toolbar using useImperativeHandle.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With