A ref is not only for the DOM: it is a sticky-note box that survives renders and suits data such as timer ids, the previous value or a mounted flag that changes without you wanting a re-render. It is lighter than state and safer than a module-level variable, because every component instance is isolated. A ref is the right home for data that describes the process rather than the interface: it has to outlive a render, but nothing on screen depends on it.
Group
Effects & Performance
Kind
Pattern
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
const timerRef = useRef(null)
timerRef.current = setInterval(...) // store
clearInterval(timerRef.current) // read
// the lazy initialization idiom:
if (ref.current === null) ref.current = expensiveInit()
Returns:No return value; this entry describes an encoding pattern rather than a function.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
Every click on +1 raises the "Current" number while "previous" keeps showing the value from before the change — the ref keeps a historical snapshot without causing extra renders.
💡 Tip Decide between state and ref like this: if the UI has to follow the value, use state; if it is only process data (a timer id, a snapshot), use a ref.
ℹ️ Info A ref is safer than a module-level variable: several instances of the same component each keep their own copy and never pollute each other.
⚠️ Warning Under concurrent rendering ref.current may be read by another render, so do not treat a ref as the primary data source of the render.
Q How do I choose between storing a value in a ref and in state?
A Content that affects the render belongs in state; intermediate data used only in event handlers and effects (ids, flags, snapshots) belongs in a ref.
Q Why does changing ref.current not trigger a render?
A React only tracks changes to state and props; a ref is an ordinary mutable object, so writing to it is plain JavaScript and never enters the render scheduler.
Q Can I write to a ref during render?
A Not except for lazy initialization (if (ref.current === null)); do the write in an event handler or a useEffect.
Web-Tutorial Tech Team
A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.