useImperativeHandle

what is useImperativeHandle() ?

  • Profile picture of Mcs
  • by Mcs July 3, 2025

useImperativeHandle() is a React Hook used with forwardRef() to customize the instance value (i.e. what a parent can access) when it uses a ref on a child component.

Why Use useImperativeHandle()?

Normally, when a parent passes a ref to a child, it gets direct access to the DOM node (e.g., an <input> element).

With useImperativeHandle(), you can:

  1. Control exactly what values or functions are exposed to the parent.
  2. Prevent direct DOM access.
  3. Expose custom functions from a child component.

Syntax

useImperativeHandle(ref, () => ({
 // values/functions to expose
}), [dependencies]);

Used Together With forwardRef()

Example: Custom Focus Method

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

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

 useImperativeHandle(ref, () => ({
   focusInput: () => {
     inputRef.current.focus();
   }
 }));

 return <input ref={inputRef} type="text" />;
});

// Parent component
function App() {
 const inputRef = useRef();

 return (
   <>
     <CustomInput ref={inputRef} />
     <button onClick={() => inputRef.current.focusInput()}>Focus</button>
   </>
 );
}

How It Works:

  1. App uses ref on <CustomInput />
  2. Inside CustomInput, useImperativeHandle() exposes only focusInput() method
  3. So App can call inputRef.current.focusInput() — but can’t access raw DOM

Benefits

FeatureWhy It’s Useful
Controlled exposureHide internal logic or DOM nodes
EncapsulationExpose only safe/public functions to parent
Custom API for componentsLet parent call child logic like reset(),openModal(), etc.

Rules

  1. Must be used with forwardRef()
  2. Typically used for custom input, modals, animations, etc.
  3. Use only when necessary — avoid overusing ref

Summary

FeatureDescription
useImperativeHandle()Customize what a ref on a child component exposes
Works withforwardRef()
Used forExposing child methods like focus(), reset()
ImprovesEncapsulation and safety

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.