useRef as Container Ref as a Container

Last updated: 2026-11-02

useRef as Container Ref as a Container

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.

GroupEffects & Performance
KindPattern

ℹ️ 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.

💡 Key Points

💡 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.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

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.com

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.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏