QuestionsReact

useRef as a mutable instance variable

RefsEasyReact

Besides pointing at a DOM node, what is useRef for? How is a ref different from state, and when do you reach for one?

What it tests

Understanding a ref as a mutable box that persists across renders WITHOUT triggering a re-render.

Approach & answer

useRef returns a stable, mutable object { current: initialValue } that persists for the component's entire lifetime — and crucially, mutating .current does NOT trigger a re-render. There are two distinct uses. (1) A handle to a DOM node: attach it via the ref attribute, then call inputRef.current.focus(). (2) A general mutable INSTANCE VARIABLE for values you must remember across renders but that should not appear on screen: an interval/timeout id, the previous value of a prop, a mutable flag like 'has the first render happened yet', a WebSocket or AbortController, or the latest callback (to escape a stale closure). The dividing line versus state: use STATE when a value change should re-render the UI; use a REF when it should not. Because a ref is just a plain object, writing ref.current = x DURING render is a foot-gun — renders must be pure, so mutate refs in event handlers and effects, not in the render body. Refs also do not notify anyone, so reading ref.current during render can hand you a stale value — never derive rendered output from a ref. Compared with a plain let: a let declared in the component body is reset to its initial value on every render, whereas a ref survives across renders; compared with a module-level variable, a ref is per-instance (each mounted component gets its own box) rather than shared. The classic precise use is capturing the previous value: store the current value into a ref inside an effect, and on the next render the ref still holds the prior one.

Use this technique when

Timer/interval ids, previous-value tracking, mutable flags, non-React object handles — anything to remember without re-rendering.

References

jsx