Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
useImperativeHandle is a React hook that allows controlling which methods and properties will be available to parent when using ref on child component.
It's used together with forwardRef to configure external interface for accessing internal component functions/values.
useImperativeHandle(ref, () => ({
// methods that will be accessible from outside
someMethod() {
// ...
},
}), [dependencies]);
ref — reference passed through forwardRef.() => ({...}) returns object with public API.[dependencies] — dependency list for object updates.focus, reset, scrollToTop, etc.).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.
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.