logo
Back to blogs

Unlocking the Power of Imperative Handles

Mar 10, 2023 - 5 min read

Unlocking the Power of Imperative Handles

Unlocking the Power of Imperative Handles in react

When working with React, sometimes we need allows child components to to expose certain function or properties to the parent component or other child components. This is where imperative handles come into play. giving you the ability to interact with the child component directly.

What are Imperative Handles?

Imperative handles allow a child component to expose methods to its parent component. This interaction is achieved using ref , which you can obtain through the useRef hook. A ref in React is an object that persists data across renders and does not trigger a re-render when updated.

Here's an example where the parent component uses a ref to call a method defined in the child component:

MyInput.tsx
1import React, { useRef, useImperativeHandle } from "react"; 2type InputAPI = { focusInput: () => void }; 3function MyInput({ 4 ref, 5 ...props 6}: React.InputHTMLAttributes<HTMLInputElement> & { 7 ref: React.RefObject<InputAPI>; 8}) { 9 const inputRef = useRef<HTMLInputElement>(null); 10 useImperativeHandle( 11 ref, 12 () => ({ focusInput: () => inputRef.current?.focus() }), 13 [] 14 ); 15 return <input ref={inputRef} {...props} />; 16} 17function App() { 18 const myInputRef = useRef<InputAPI>(null); 19 return ( 20 <div> 21 <MyInput ref={myInputRef} placeholder="Enter your name" /> 22 <button onClick={()=> myInputRef.current?.focusInput()}> 23 Focus the input 24 </button> 25 </div> 26 ); 27}