Repository navigation
useImperativeHandle
vinibiavatti1 edited this page Sep 28, 2026
·
3 revisions
Customizes the handle exposed as a ref to a parent component. It allows a child component to expose specific imperative methods rather than the raw DOM node.
import { forwardRef, useRef, useEffect, useImperativeHandle } from 'react';
// Custom element with forwardRef
export const Input = forwardRef((props, ref) => {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
customFocus: () => inputRef.current?.focus() // Transform exposed properties
}), []);
return (
<input ref={inputRef} />
);
});
// Only the exposed properties (customFocus) will be available on parent ref
export const Form = () => {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.customFocus(); // OK
// inputRef.current?.focus(); -> Error: undefined!
}, []);
return (
<Input ref={inputRef} /> // Can be referenced by ref
);
};- Home
- Functional Components
- Props
- Fragments
- Memoization
- Forward Ref
- Portals
- Suspense
-
Hooks
- State
- Context
- Effect
- Ref
- Performance
- Concurrent
- Form
- Utility
- Custom Hooks