الانتقال إلى المحتوى
FrontendReact· 7 دقائق للقراءة

Refs Are an Escape Hatch, Not State That Skips Re-renders

React hands you the same ref every render and never watches it. Anything the screen shows belongs in state.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

A performance review flags the post composer: it re-renders on every keystroke. The fix looks clever: move the text from state into a ref, so typing no longer renders anything. It ships, and the bug reports follow. The "0/280" counter never moves, and the Post button stays disabled however much you type. Then a notification arrives, something unrelated re-renders the composer, and the counter suddenly jumps to "143/280". React wasn't broken. The component was showing a value React had no idea existed.

The common misconception

The belief: useRef is useState without the re-render. It's a cheaper box for any value: write to it whenever you like, read it in JSX, and save renders along the way.

There's a lot of truth in it, which is why it sticks. A ref does persist across renders like state, and changing it doesn't re-render, which is exactly how React's docs introduce refs: a way to remember information without triggering new renders. The docs even note that useRef could in principle be built on top of useState. And "avoid unnecessary re-renders" is advice every React developer hears early. What the belief leaves out is the other half: React never looks at a ref, so nothing that depends on it updates by itself, and touching it during render makes the component impure.

What actually happens

A ref is a box React hands back and never watches

useRef(initialValue) returns a plain object, { current: initialValue }, and on every later render it returns that same object. You can change ref.current at any time, and the change is visible immediately, with no snapshot and no queue. React doesn't know when that happens, so it schedules nothing. That's the whole feature, and it's why React's docs call an : they let you step outside React's data flow, which is useful exactly when the value has nothing to do with what's on screen.

Rendering from a ref shows a stale value

JSX that reads ref.current captures whatever the ref held when the component last rendered for some other reason. Typing changes the ref but triggers no render, so the counter keeps its old value until an unrelated state change happens to re-render the composer. The rule from React's docs is simple: if a value is used for rendering, keep it in state.

TSX Composer.tsx
import { useRef } from "react";export function Composer() {  // "Saves re-renders", and freezes everything that shows the text  const textRef = useRef("");  const length = textRef.current.length; // read during render: stale  return (    <>      <textarea onChange={(e) => { textRef.current = e.target.value; }} />      <span>{length}/280</span>      <button disabled={length === 0}>Post</button>    </>  );}

If re-rendering on every keystroke is a real, measured problem, the fix is to keep the text in the smallest component that shows it, not to hide it from React. Re-rendering a textarea, a counter and a button is cheap.

Reading or writing during render is a side effect

The other half of the rule is about the component body. Patterns like renderCount.current++ or previous.current = value at the top level of a component write to a ref during render. React expects render to be a : it may call your component twice in Strict Mode, or start a render and throw it away. A ref write from a render that never reached the screen still happened, so the ref ends up describing renders the user never saw. Reading during render is just as unreliable: a DOM ref is still null on the first render, because React only sets it during the commit. React's docs warn that such a component might still work, but most of the newer features React is adding rely on render staying pure.

The one exception is lazy initialization: if (ref.current === null) ref.current = new VideoPlayer() runs once, always produces the same result, and is allowed. For a previous value that the output depends on, use state, as the useState docs do with a stored prevCount.

What refs are actually for

React's docs list a short set of jobs: storing timeout and interval ids, holding DOM nodes, and keeping other objects that aren't needed to calculate the JSX, like an instance of a third-party player or map. All of them are read and written in event handlers and Effects, never during render:

TSX SearchBox.tsx
import { useRef, useState } from "react";export function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {  const [query, setQuery] = useState(""); // shown on screen: state  const timerRef = useRef<number | undefined>(undefined); // never shown: ref  function handleChange(next: string) {    setQuery(next);    clearTimeout(timerRef.current); // cancel the search still pending    timerRef.current = window.setTimeout(() => onSearch(next), 300);  }  return <input value={query} onChange={(e) => handleChange(e.target.value)} />;}

The query appears in the input, so it's state. The timer id never appears anywhere; only the next keystroke needs it, to cancel the pending search, so it's a ref.

QuestionStateRef
Changing itRe-renders the componentRe-renders nothing
When a new value is visibleIn the next render; each render keeps a snapshotImmediately: it's a plain object
Reading it during renderThat's what it's forNot allowed, except one-time initialization
Where you change itThrough the setter, in handlers or EffectsDirectly, in handlers or Effects
Typical contentsAnything the JSX showsTimer ids, DOM nodes, non-React objects

How to apply it in your project

  1. Turn on the refs lintThe recommended preset of eslint-plugin-react-hooks includes a refs rule that flags reading or writing ref.current during render. Fix what it reports instead of disabling it.
  2. Search for `.current` outside handlers and EffectsLook in JSX and at the top level of component bodies. Each hit is a value the screen may show stale, or a write that can happen for renders React throws away.
  3. Sort each value with one questionDoes the output depend on it? Then it's state. Do only handlers and Effects need it? Then a ref is fine.
  4. Keep DOM refs for what React can't doUse them to focus, scroll, measure and drive third-party widgets, and leave adding and removing elements to React.

Key takeaways

  • A ref is a mutable box React returns on every render but never watches, so changing it re-renders nothing.
  • Anything the JSX shows belongs in state; a ref read during render shows whatever it held at the last render.
  • Don't read or write ref.current during render, except one-time lazy initialization; use handlers and Effects.
  • Refs are the escape hatch for timer ids, DOM nodes and non-React objects, not a faster kind of state.

📚 المصادر

  1. Referencing Values with Refs — React
  2. useRef — React API Reference
  3. Manipulating the DOM with Refs — React
  4. refs — eslint-plugin-react-hooks
  5. React v19 — React Blog

التعليقات (0)