Skip to main content
InterviewHubPRO
Section Overview
Q300

Question 300 of 407

Part 9: React Hooks Deep Dive (262 - 316)

74%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

When should you use useImperativeHandle?

mid LevelCode ExampleHooks

The useImperativeHandler hook will be used in below cases:

  • You want to expose imperative methods from a child component
    • Custom input controls exposing focus, clear, or validate methods
    • Modal components exposing open() and close() methods
    • Scroll containers exposing scrollToTop() or scrollToBottom() methods
  • You want to hide internal implementation but provide controlled external access.
  • You're building reusable component libraries (e.g., inputs, modals, form controls).

Practical Code Example

jsx
// When to use useImperativeHandle:
// Exposing specialized imperatively triggered methods (e.g. focus, clear, scroll)
import { forwardRef, useImperativeHandle, useRef } from 'react';

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

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

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