Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Understanding useImperativeHandle Hook

Learn how to customize the instance value exposed to parent components when using ref with useImperativeHandle. Control what parent components can access via refs.

jiocoder TeamUpdated Jun 6, 20263 min readReact
Understanding useImperativeHandle Hook

What is useImperativeHandle?#

useImperativeHandle is a React hook that allows you to customize the instance value that is exposed to parent components when using ref. It's typically used with forwardRef to expose specific methods or properties instead of the entire DOM element or component instance.

This hook is useful when you want to control what parent components can access through refs. Instead of exposing the entire component instance or DOM node, you can expose only the methods and properties you want to make available, creating a cleaner API.

Installation#

useImperativeHandle is part of React core (React 16.8+), so no additional installation is needed. Verify your React version:

Code
npm list react

Basic Syntax#

Code
useImperativeHandle(ref, createHandle, [deps])

Example: Custom Input Component#

Let's create a custom input component that exposes only specific methods:

Code
import { forwardRef, useImperativeHandle, useRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef(null);
  
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    blur: () => {
      inputRef.current.blur();
    },
    getValue: () => {
      return inputRef.current.value;
    },
    setValue: (value) => {
      inputRef.current.value = value;
    },
    clear: () => {
      inputRef.current.value = '';
      inputRef.current.focus();
    },
    select: () => {
      inputRef.current.select();
    }
  }));
  
  return (
    <input
      ref={inputRef}
      type="text"
      {...props}
      className="custom-input"
    />
  );
});

CustomInput.displayName = 'CustomInput';

// Usage in parent component
function Form() {
  const inputRef = useRef(null);
  
  const handleFocus = () => {
    inputRef.current.focus();
  };
  
  const handleClear = () => {
    inputRef.current.clear();
  };
  
  const handleGetValue = () => {
    const value = inputRef.current.getValue();
    console.log('Input value:', value);
  };
  
  return (
    <div>
      <CustomInput ref={inputRef} placeholder="Enter text" />
      <button onClick={handleFocus}>Focus Input</button>
      <button onClick={handleClear}>Clear Input</button>
      <button onClick={handleGetValue}>Get Value</button>
    </div>
  );
}

Example: Modal Component#

Creating a modal that exposes open and close methods:

Code
import { forwardRef, useImperativeHandle, useState } from 'react';

const Modal = forwardRef(({ children, onClose }, ref) => {
  const [isOpen, setIsOpen] = useState(false);
  
  useImperativeHandle(ref, () => ({
    open: () => setIsOpen(true),
    close: () => {
      setIsOpen(false);
      onClose?.();
    },
    toggle: () => setIsOpen(prev => !prev),
    isOpen: () => isOpen
  }));
  
  if (!isOpen) return null;
  
  return (
    <div className="modal-overlay" onClick={() => setIsOpen(false)}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <button className="close-button" onClick={() => setIsOpen(false)}>
          ×
        </button>
        {children}
      </div>
    </div>
  );
});

Modal.displayName = 'Modal';

// Usage
function App() {
  const modalRef = useRef(null);
  
  return (
    <div>
      <button onClick={() => modalRef.current.open()}>Open Modal</button>
      <button onClick={() => modalRef.current.close()}>Close Modal</button>
      <button onClick={() => modalRef.current.toggle()}>Toggle Modal</button>
      
      <Modal ref={modalRef} onClose={() => console.log('Modal closed')}>
        <h2>Modal Content</h2>
        <p>This is modal content</p>
      </Modal>
    </div>
  );
}

Example: Form Component#

Expose form validation and submission methods:

Code
const Form = forwardRef((props, ref) => {
  const [formData, setFormData] = useState({});
  const [errors, setErrors] = useState({});
  
  useImperativeHandle(ref, () => ({
    validate: () => {
      const newErrors = {};
      if (!formData.name) newErrors.name = 'Name is required';
      if (!formData.email) newErrors.email = 'Email is required';
      setErrors(newErrors);
      return Object.keys(newErrors).length === 0;
    },
    getValues: () => formData,
    setValues: (values) => setFormData(values),
    reset: () => {
      setFormData({});
      setErrors({});
    },
    submit: () => {
      if (validate()) {
        // Submit logic
        return formData;
      }
      return null;
    }
  }));
  
  return (
    <form>
      {/* Form fields */}
    </form>
  );
});

When to Use useImperativeHandle#

  • Creating reusable component libraries
  • Exposing specific methods instead of entire instances
  • Controlling what parent components can access
  • Creating imperative APIs for declarative components
  • Integrating with third-party libraries that require refs

When NOT to Use#

  • Most cases - prefer declarative props and callbacks
  • When you can solve the problem with props
  • For simple DOM access - use refs directly
  • When it makes the API less React-like

Best Practices#

  • Use sparingly - prefer declarative props when possible
  • Only expose necessary methods
  • Document the exposed API clearly
  • Consider using callbacks instead for better React patterns
  • Keep the exposed API minimal and focused
  • Use TypeScript to type the exposed handle

TypeScript Example#

Code
interface CustomInputHandle {
  focus: () => void;
  blur: () => void;
  getValue: () => string;
  setValue: (value: string) => void;
  clear: () => void;
}

const CustomInput = forwardRef<CustomInputHandle, InputProps>((props, ref) => {
  const inputRef = useRef<HTMLInputElement>(null);
  
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current?.focus(),
    blur: () => inputRef.current?.blur(),
    getValue: () => inputRef.current?.value || '',
    setValue: (value: string) => {
      if (inputRef.current) {
        inputRef.current.value = value;
      }
    },
    clear: () => {
      if (inputRef.current) {
        inputRef.current.value = '';
        inputRef.current.focus();
      }
    }
  }));
  
  return <input ref={inputRef} {...props} />;
});

useImperativeHandle is a powerful but advanced hook that should be used sparingly. It's most useful when building reusable component libraries or when you need to integrate with imperative APIs. In most cases, prefer declarative React patterns with props and callbacks.

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment