ReactHard
What is useImperativeHandle?
useImperativeHandle(ref, () => handle, deps) customizes what a parent receives through a ref. Instead of exposing the whole DOM node, a component exposes a small object of methods such as focus(), scrollToBottom() or play(). In React 19, ref arrives as a normal prop, so you no longer need forwardRef to use it.
When to use it
- Imperative actions that do not fit props: focus, select text, scroll, play or pause media, open a native dialog, trigger an animation.
- Hiding internals: expose
focus()but not the input node, so parents cannot mutate styles or the DOM. - Combining several inner refs into one API.
When not to
If it can be expressed as props (isOpen, value), use props. Imperative handles make data flow harder to follow and should be the exception.
How it works
- The component receives
refas a prop (React 19), or viaforwardRefin React 18 and earlier. - It keeps its own internal refs to DOM nodes.
useImperativeHandle(ref, () => ({ focus() { inputRef.current?.focus(); } }), [])setsref.currentto that object.- The parent calls
childRef.current?.focus()in an event handler or effect.
TypeScript
Define a handle type and use React.Ref<Handle> for the prop; the parent uses useRef<Handle>(null).
Code example
tsx
1import { useImperativeHandle, useRef } from "react";23export type VideoHandle = { play: () => void; pause: () => void; seek: (t: number) => void };45// React 19: ref is a regular prop, no forwardRef needed6function VideoPlayer({ src, ref }: { src: string; ref?: React.Ref<VideoHandle> }) {7 const videoRef = useRef<HTMLVideoElement>(null);89 useImperativeHandle(ref, () => ({10 play: () => void videoRef.current?.play(),11 pause: () => videoRef.current?.pause(),12 seek: (t) => {13 if (videoRef.current) videoRef.current.currentTime = t;14 },15 }), []);1617 return <video ref={videoRef} src={src} width={480} />;18}1920export function Lesson() {21 const player = useRef<VideoHandle>(null);22 return (23 <div>24 <VideoPlayer ref={player} src="/lesson-1.mp4" />25 <button onClick={() => player.current?.play()}>Play</button>26 <button onClick={() => player.current?.pause()}>Pause</button>27 <button onClick={() => player.current?.seek(60)}>Jump to 1:00</button>28 </div>29 );30}
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 set.