👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
useImperativeHandle: methods a parent calls through ref
useImperativeHandle chooses which methods a parent can call through a ref on a child. Without it, the ref points at a DOM node, not at methods such as focus or reset. Use it together with forwardRef.
Hooks from interviews: React interview problems.
Syntax
useImperativeHandle(ref, () => ({
// methods that will be accessible from outside
someMethod() {
// ...
},
}), [dependencies]);
ref— reference passed throughforwardRef.- Function
() => ({...})returns object with public API. [dependencies]— dependency list for object updates.
When useImperativeHandle is Needed
- When you want to limit access to internal component functions (encapsulation).
- When you need to expose child component methods to parent (e.g.,
focus,reset,scrollToTop, etc.). - When working with non-standard or complex DOM elements, custom components, modal windows, etc.
Example: accessing focus method from parent
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current?.focus();
},
clear: () => {
inputRef.current!.value = '';
}
}));
return <input ref={inputRef} {...props} />;
});
export default function App() {
const inputRef = useRef<{ focus: () => void; clear: () => void }>(null);
return (
<div>
<CustomInput ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus</button>
<button onClick={() => inputRef.current?.clear()}>Clear</button>
</div>
);
}
Important:
useImperativeHandle works only inside components wrapped in forwardRef.
Conclusion
useImperativeHandle is an advanced React tool used in cases when you need to explicitly configure component access interface via ref. This is convenient for creating controlled components, modal windows, custom inputs and other situations where parent needs to directly manage child behavior.