MyInternships.in

React Hooks

React useImperativeHandle Hook

useImperativeHandle customises what a parent receives through a ref. Instead of exposing the raw DOM node, you expose a small object of methods you choose — a deliberate, narrow API.


What is useImperativeHandle Hook in React?

useImperativeHandle customises what a parent receives through a ref. Instead of exposing the raw DOM node, you expose a small object of methods you choose — a deliberate, narrow API.

Why useImperativeHandle Hook matters

Handing out the raw node lets a parent do anything, including changes React will overwrite. Exposing focus() and clear() keeps the component’s internals private and its contract explicit.

useImperativeHandle Hook example

Exposing two methods, not the node
JSX
const OtpInput = forwardRef(function OtpInput(props, ref) {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    clear: () => { inputRef.current.value = ''; },
  }), []);

  return <input ref={inputRef} maxLength={6} />;
});

// parent
otpRef.current.focus();
otpRef.current.clear();   // and nothing else

Key points to remember

  • Always used together with forwardRef (or a ref prop in React 19).
  • The dependency array controls when the exposed object is rebuilt.
  • Use sparingly — imperative APIs work against React’s declarative model.

Common mistakes with useImperativeHandle Hook

  • Exposing a method that mutates DOM React manages, which the next render undoes.
  • Reaching for it when a prop would express the same intent declaratively.

React useImperativeHandle Hook— Interview Questions & FAQs

When should I use useImperativeHandle?+

When a parent genuinely needs to trigger an action — focus, scroll into view, play, reset — that cannot be expressed as a prop. For anything state-driven, a prop is the better tool.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships