🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Refs, Focus, and Imperative DOM Control in React

React FundamentalsRefsđŸŸĸ Free Lesson

What You'll Learn

  • 1Decide when a problem needs a ref rather than another piece of state
  • 2Measure an element safely with a callback ref and clean it up on unmount
  • 3Expose a narrow imperative API from a child with useImperativeHandle
  • 4Avoid the ref anti-patterns that hide updates or leak timers

When the declarative model runs out

React's model is that you describe the screen for a given state and React applies the difference. That covers most problems, but not all of them. Focusing an input, scrolling a container into view, reading an element's measured size, starting a video, or clearing a timer you started earlier are all things you need to do to the world directly, and none of them belong in the render output.

Refs are the escape hatch. A ref is a container object that React neither renders nor re-renders on assignment. Writing to its current property does not schedule anything, which is precisely why it is the right place for values that exist for the component's lifetime but never appear in the UI: timers, subscription handles, previous values, and the DOM node you intend to poke.

The dividing line is simple. If the value should appear on screen, use state. If the value is bookkeeping that helps you talk to the browser or an external system, use a ref.

A persistent box for mutable values

The most common ref workload is holding something you later have to clean up. Because the ref object is the same across renders, the cleanup function and the event handler that both need the timer agree on which timer is current.

import { useEffect, useRef, useState } from 'react';

function Stopwatch() {
  const [elapsed, setElapsed] = useState(0);
  const [running, setRunning] = useState(false);
  const startedAt = useRef(0);
  const accumulated = useRef(0);
  const frame = useRef(null);

  useEffect(() => {
    if (!running) return undefined;

    startedAt.current = performance.now();
    const tick = () => {
      setElapsed(accumulated.current + (performance.now() - startedAt.current));
      frame.current = requestAnimationFrame(tick);
    };
    frame.current = requestAnimationFrame(tick);

    return () => {
      accumulated.current += performance.now() - startedAt.current;
      cancelAnimationFrame(frame.current);
    };
  }, [running]);

  const reset = () => {
    accumulated.current = 0;
    setElapsed(0);
  };

  return (
    <div>
      <p>{(elapsed / 1000).toFixed(2)}s</p>
      <button type="button" onClick={() => setRunning((r) => !r)}>
        {running ? 'Pause' : 'Start'}
      </button>
      <button type="button" onClick={reset}>Reset</button>
    </div>
  );
}

Note the division of labour. Elapsed time is state because it drives the display. The animation frame handle, the start timestamp, and the accumulated milliseconds are refs because nothing on screen depends on them directly, and re-rendering on every frame would be wasted work if the display changed only ten times a second.

Callback refs for measurement

When you need an element to do something imperative, a callback ref runs whenever the node is attached or detached. That is more useful than a plain ref for measurement and for wiring third-party libraries, because you can set up in one call and tear down in the other, with no effect required.

function useElementWidth() {
  const [width, setWidth] = useState(0);
  const observerRef = useRef(null);

  const ref = (node) => {
    if (observerRef.current) observerRef.current.disconnect();
    if (!node) return;

    observerRef.current = new ResizeObserver((entries) => {
      const entry = entries[0];
      if (entry) setWidth(Math.round(entry.contentRect.width));
    });
    observerRef.current.observe(node);
    setWidth(Math.round(node.getBoundingClientRect().width));
  };

  useEffect(() => () => observerRef.current?.disconnect(), []);

  return [ref, width];
}

function ResponsiveBanner({ title }) {
  const [ref, width] = useElementWidth();
  const density = width > 720 ? 'comfortable' : 'compact';

  return (
    <section ref={ref} className={`banner ${density}`}>
      <h2>{title}</h2>
      {density === 'comfortable' && <p>Full description shown at this width.</p>}
    </section>
  );
}

The disconnect call at the top of the callback covers the case where React detaches the old node before attaching the new one, which happens whenever the element moves in the tree. Forgetting it leaks an observer and keeps a detached node alive.

Exposing a narrow imperative API

Sometimes a component needs to be driven from outside: a media player that a toolbar should control, or an input a parent wants to focus. Passing the raw DOM node up couples the parent to the child's internals. useImperativeHandle lets the child publish a curated surface instead.

import { forwardRef, useImperativeHandle, useRef } from 'react';

const MediaPlayer = forwardRef(function MediaPlayer({ src }, ref) {
  const audioRef = useRef(null);

  useImperativeHandle(ref, () => ({
    play: () => audioRef.current?.play(),
    pause: () => audioRef.current?.pause(),
    seek: (seconds) => {
      if (audioRef.current) audioRef.current.currentTime = seconds;
    },
  }), []);

  return <audio ref={audioRef} src={src} controls />;
});

function Toolbar() {
  const playerRef = useRef(null);

  return (
    <div className="toolbar">
      <MediaPlayer ref={playerRef} src="/media/episode-1.mp3" />
      <button type="button" onClick={() => playerRef.current?.play()}>Play</button>
      <button type="button" onClick={() => playerRef.current?.pause()}>Pause</button>
      <button type="button" onClick={() => playerRef.current?.seek(30)}>Skip 30s</button>
    </div>
  );
}

The dependency array keeps the handle stable, so the parent's references stay valid across renders. If the handle depends on props or state, list them, and remember the parent gets the new object only after the child re-renders.

Focus management that actually works

Keyboard support is the most common reason a component needs an imperative handle at all, and it is also where refs are used most carelessly. A form that moves focus between steps needs to know which element will exist in the next render, not which one exists now, so the focus call belongs in an effect that runs after the commit rather than in the handler that changes the state.

The same applies to validation. Focusing the first invalid field after a failed submit is a small courtesy with a large effect on completion rates, and it requires a ref to the field so you can call focus on the node rather than trying to express focus as state. Keep a list of the controls in order, find the first whose error is set, and focus it in an effect keyed on the submit attempt counter.

Autofocus deserves caution. Focusing an input on mount is correct for a dialog and jarring for a page section that scrolls into view, so scope it. And remember that programmatically focusing an element scrolls the page as well; in a long form, that scroll is often the behaviour the user wanted, but inside a small panel it can hide the field you just focused. Use focus with the preventScroll option when the surrounding layout already keeps the element visible.

What each kind of ref is good for

JobToolNotes
Focusing or blurring an inputPlain ref plus an effectFocus on mount or when a field becomes active
Scrolling to an elementPlain refPrefer scrollIntoView with explicit behaviour
Measuring sizeCallback ref with ResizeObserverDisconnect in the callback and in cleanup
Watching position while scrollingCallback ref with IntersectionObserverEssential for lazy content and infinite lists
Holding a timer handlePlain refClear it in effect cleanup, never in render
Remembering the previous valuePlain ref updated in an effectWriting during render is a side effect and is unsafe
Wiring a third-party widgetCallback refAttach on mount, destroy on detach
Exposing methods to a parentforwardRef with useImperativeHandlePublish the smallest surface you can

The resources a ref tends to own

Almost every ref that holds a live resource needs a corresponding release, and the release has to happen exactly once. Timers created with setTimeout or setInterval, animation frames, observers for size and visibility, event listeners attached to the document or the window, WebSocket and EventSource connections, and third-party instances created in an effect are all in this category. Each one keeps something alive that React does not know about, so unmounting the component does not clean any of it up.

The reliable pattern is the one the effect contract already gives you: acquire in the effect body, return a cleanup that releases, and let React call that cleanup before the next run and on unmount. When two parts of the component need the same handle, such as a click handler that cancels a timer started in an effect, the ref is the shared slot they both read, and the cleanup remains the single place that cancels.

Watch for the asymmetric case where the resource is created in an event handler rather than in an effect. A subscription started when the user presses play must be ended when the component unmounts, which means the cleanup path cannot live only in an effect that has already run. Track the active resource in a ref, and let the unmount cleanup check whether anything is currently active before releasing it.

Myths worth retiring

A popular misconception is that reading a ref during render gives you a cheap way to branch on the DOM. It does not, because the first render has no node yet and the value is not reactive, so nothing re-renders when it arrives. Measure in a callback ref or an effect instead.

Another is that refs must be cleared manually before unmount. React nulls the ref when the node is removed, so your job is to release the resources that node owned: observers, intervals, listeners, and third-party instances. And writing a ref during render, rather than in an effect or a callback, breaks with concurrent rendering, because render may be thrown away and re-run.

Common Mistakes

Storing displayable data in a ref so updates do not re-render

Fix: Use state for anything the UI shows and refs only for imperative bookkeeping

Forgetting to disconnect an observer or clear an interval attached through a ref

Fix: Return cleanup from effects and disconnect inside callback refs when the node changes

Exposing the whole component instance to the parent through a ref

Fix: Publish a small object with useImperativeHandle that describes only the operations you support

Reading or writing a ref during render to avoid an effect

Fix: Move ref writes into effects, event handlers, or callback refs so concurrent render stays safe

Best Practices

  • Name the question first: is this value rendered, or is it bookkeeping for the browser
  • Prefer callback refs with observers over manual measurement in layout effects
  • Keep imperative handles stable with an empty dependency array unless they truly depend on state
  • Clear every resource you acquire through a ref when the component unmounts
  • Use the native dialog and media elements where they already provide the imperative API you need

Key Takeaways

  • Refs are containers that survive renders without triggering them, ideal for timers and DOM nodes
  • Callback refs run on attach and detach, which makes them the natural home for observers
  • useImperativeHandle exposes a curated API instead of leaking a child's internals upward
  • Ref writes belong in effects and handlers, never in the render body
  • Rendering state, imperative bookkeeping in refs: keeping that line clear prevents most ref bugs
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement