What is useImperativeHandle?

useImperativeHandle is an advanced hook used to customize the instance value that is exposed to parent components when using a ref.

The Problem:

Normally, when you pass a ref down to a custom child component using forwardRef, the parent gets complete, raw access to the underlying DOM node (like <input>). Sometimes, you don't want the parent to have full access to the DOM node; you only want to expose a specific set of controlled methods (an "imperative API").

The Solution:

useImperativeHandle(ref, createHandle) allows the child component to intercept the ref and dictate exactly what object is bound to ref.current in the parent.

Common Use Cases:

  • Hiding raw DOM nodes and exposing only .focus() or .scrollIntoView().
  • Building complex UI components (like Modals or Drawers) where the parent needs to trigger .open() or .close() programmatically without relying on state props.

Code example

tsx
1import React, { useRef, useImperativeHandle, forwardRef, useState } from 'react';
2
3// 1. Child Component uses forwardRef and useImperativeHandle
4const CustomModal = forwardRef((props, ref) => {
5 const [isOpen, setIsOpen] = useState(false);
6
7 // We define exactly what the parent is allowed to do via the ref
8 useImperativeHandle(ref, () => ({
9 openModal: () => setIsOpen(true),
10 closeModal: () => setIsOpen(false),
11 // The parent CANNOT access the raw <div> or internal state directly!
12 }));
13
14 if (!isOpen) return null;
15
16 return (
17 <div className="fixed inset-0 bg-black/50 flex justify-center items-center backdrop-blur-sm z-50">
18 <div className="bg-white p-8 rounded-2xl shadow-2xl max-w-sm w-full text-center">
19 <h2 className="text-2xl font-bold mb-4">Imperative Modal</h2>
20 <p className="text-gray-600 mb-6">Controlled entirely via refs!</p>
21 <button
22 onClick={() => setIsOpen(false)}
23 className="bg-red-500 text-white px-6 py-2 rounded-lg font-semibold w-full hover:bg-red-600"
24 >
25 Close Internally
26 </button>
27 </div>
28 </div>
29 );
30});
31
32// 2. Parent Component
33export default function App() {
34 // Create a ref to hold the imperative handle from the child
35 const modalRef = useRef();
36
37 return (
38 <div className="p-12 text-center">
39 <h1 className="text-3xl font-extrabold mb-8">Parent Component</h1>
40
41 <button
42 // Calling the custom method exposed by useImperativeHandle
43 onClick={() => modalRef.current.openModal()}
44 className="bg-indigo-600 text-white px-8 py-4 rounded-xl shadow-lg font-bold text-lg hover:bg-indigo-700 transition"
45 >
46 Open Modal from Parent
47 </button>
48
49 <CustomModal ref={modalRef} />
50 </div>
51 );
52}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.

Open in study app