AceDevHub
Intermediate React Interview QuestionsIntermediatePractical

React · Question 63

When would you use useImperativeHandle in React?

Direct answer

Use useImperativeHandle when a component must expose a small, intentional imperative API through a ref instead of exposing its entire DOM node or internal implementation.

SearchInput.jsx
function SearchInput({ ref }) {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focus() {
      inputRef.current?.focus();
    },
    select() {
      inputRef.current?.select();
    }
  }), []);

  return <input ref={inputRef} />;
}
  • Good fit: focus, scrolling, text selection, imperative animation, or integration with non-React APIs.
  • Prefer props: when the behavior can be expressed declaratively, such as isOpen, value, or selected.