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
1import React, { useRef, useImperativeHandle, forwardRef, useState } from 'react';23// 1. Child Component uses forwardRef and useImperativeHandle4const CustomModal = forwardRef((props, ref) => {5 const [isOpen, setIsOpen] = useState(false);67 // We define exactly what the parent is allowed to do via the ref8 useImperativeHandle(ref, () => ({9 openModal: () => setIsOpen(true),10 closeModal: () => setIsOpen(false),11 // The parent CANNOT access the raw <div> or internal state directly!12 }));1314 if (!isOpen) return null;1516 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 <button22 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 Internally26 </button>27 </div>28 </div>29 );30});3132// 2. Parent Component33export default function App() {34 // Create a ref to hold the imperative handle from the child35 const modalRef = useRef();3637 return (38 <div className="p-12 text-center">39 <h1 className="text-3xl font-extrabold mb-8">Parent Component</h1>4041 <button42 // Calling the custom method exposed by useImperativeHandle43 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 Parent47 </button>4849 <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.