
Refs Are an Escape Hatch, Not State That Skips Re-renders
- كاتب موثّق
- React 19
محتويات المقال
The common misconception
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.
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
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.
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> </> );}import { useState } from "react";export function Composer() { // Shown on screen, so it's state: every keystroke updates the counter const [text, setText] = useState(""); return ( <> <textarea value={text} onChange={(e) => setText(e.target.value)} /> <span>{text.length}/280</span> <button disabled={text.length === 0}>Post</button> </> );}Reading or writing during render is a side effect
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.
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
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)} />;}How to apply it in your project
Turn on the refs lint The recommended preset of eslint-plugin-react-hooksincludes arefsrule that flags reading or writingref.currentduring render. Fix what it reports instead of disabling it.Search for `.current` outside handlers and Effects Look 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. Sort each value with one question Does the output depend on it? Then it's state. Do only handlers and Effects need it? Then a ref is fine. Keep DOM refs for what React can't do Use 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.currentduring 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.
التعليقات (0)