Skip to article content
FrontendXLesson 19 / 40

Imperative Handles with useImperativeHandle

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

advanced · about 50 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Interview

What you will be able to do

#
  • Expose a narrow imperative API from a child through a ref.
  • Use ref as a prop in React 19 without forwardRef.
  • Decide when an imperative handle is justified.

Overview

#

Exposing a narrow API

Sometimes a parent needs to call methods on a child, such as focus, play or scroll. Reaching into the child's DOM from outside breaks encapsulation. useImperativeHandle lets the child expose exactly the methods you choose through a ref.

snippet.tsx
type InputHandle = { focus: () => void; clear: () => void };
type TextInputProps = { placeholder?: string; ref?: React.Ref<InputHandle> };

function TextInput({ ref, ...props }: TextInputProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current?.focus(),
    clear: () => { if (inputRef.current) inputRef.current.value = ''; },
  }), []);
  return <input ref={inputRef} {...props} />;
}

In React 19 the child reads ref from its props, so no forwardRef wrapper is required. A plain function component receives only the props object as its first argument; declaring a second ref parameter does not receive the ref and leaves useImperativeHandle with undefined.

The dependency array

The third argument controls when the handle is recreated. An empty array creates it once. If the handle closes over values that change, list them so the exposed methods see the latest values.

When not to use it

Imperative handles are an escape hatch. Prefer props and state: pass an isOpen prop instead of calling open(). Reach for an imperative handle only for actions that are inherently imperative, such as focus, media playback, scrolling or animation control.

Pitfall: exposing the whole DOM node

The ref should expose the smallest useful API, not the raw node. If the parent can do anything, the component has no interface and is hard to replace or test.

Pitfall: stale closures in the handle

If a method reads a prop or state and you pass an empty dependency array, it captures the first value forever. Include the values the methods read.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    The parent calls handle.focus(). Does the input receive focus?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    type Handle = { focus: () => void };
    
    function TextInput({ ref }: { ref?: React.Ref<Handle> }) {
      const inputRef = useRef<HTMLInputElement>(null);
      useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }), []);
      return <input ref={inputRef} />;
    }
    
    const ref = useRef<Handle>(null);
    <TextInput ref={ref} />;
    ref.current?.focus();
    Choose the best answer
  2. Exercise 2Implement

    Expose only play and pause from a video component through its ref.

    starter.tsx
    export function Video({ src }: { src: string }) {
      return <video src={src} />;
    }

    Reveal the reference answer
    reference.tsx
    export type VideoHandle = { play: () => void; pause: () => void };
    
    export function Video({ src, ref }: { src: string; ref: React.Ref<VideoHandle> }) {
      const videoRef = useRef<HTMLVideoElement>(null);
      useImperativeHandle(ref, () => ({
        play: () => videoRef.current?.play(),
        pause: () => videoRef.current?.pause(),
      }), []);
      return <video ref={videoRef} src={src} />;
    }

    Authored expected output: A parent holding the ref can call play and pause but cannot reach other video methods.

    The handle returns an object with exactly play and pause, delegating to the internal element. The parent cannot access the raw video node, which keeps the component's interface small.

  3. Exercise 3Debug

    The exposed method logs a stale count. Explain and fix.

    starter.tsx
    useImperativeHandle(ref, () => ({ report: () => console.log(count) }), []);

    Reveal the reference answer
    reference.tsx
    useImperativeHandle(ref, () => ({ report: () => console.log(count) }), [count]);

    Authored expected output: report logs the current count.

    With an empty dependency array the handle is created once and captures the first count. Listing count recreates the handle when it changes so the method reads the latest value.

  4. Exercise 4Interview

    When would you expose an imperative handle instead of using props, and what are the risks?

    starter.tsx
    // focus, media playback, scroll, animation

    Reveal the reference answer
    reference.tsx
    Use an imperative handle for actions that are inherently imperative and cannot be expressed as declarative state, such as focusing an input, playing media, scrolling to a position or driving an animation. The risks are that imperative code is harder to test, breaks the one-way data flow, and can capture stale values if the dependency array is wrong. Keep the exposed API as small as possible and prefer props and state for everything that can be described declaratively.

    Authored expected output: A justified use case plus the encapsulation, testing and staleness risks.

    The answer should treat the handle as an escape hatch with real costs, not a default tool.

Common misconceptions

#
  • You must wrap the component in forwardRef in React 19. ref is a normal prop, so forwardRef is optional.
  • The handle should expose the DOM node. Expose the smallest API the parent needs.
  • useImperativeHandle is the preferred way to control a child. Prefer props and state; use it only for imperative actions.
  • The dependency array is always empty. Include the values the exposed methods read, or they go stale.

Follow-up practice

#
  • react-portals
  • react-custom-hooks

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.