What is useImperativeHandle in React?

useImperativeHandle is a React hook that customizes the instance value that is exposed when a parent component uses ref on a child component. It allows you to define imperative methods that can be called on the child component by its parent.

Use useImperativeHandle when:

  • You need to expose methods or properties from a child component to its parent.
  • The child component needs to provide a controlled imperative API (e.g., managing focus, animations, or scrolling).
import React, { useRef, forwardRef, useImperativeHandle } from "react";

const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();

useImperativeHandle(
ref,
() => ({
focus: () => {
inputRef.current.focus();
},
clear: () => {
inputRef.current.value = "";
},
}),
[] // No dependencies, as nothing dynamic is involved
);

return <input ref={inputRef} {...props} />;
});

When Dependencies Are Needed: If the imperative methods rely on props, state, or dynamic logic, you must include them in the dependency array.