useRef Ref Hook

Last updated: 2026-11-02

useRef Ref Hook

useRef returns a container with a current property: it keeps any value alive across renders, and writing to it never triggers a re-render. The most common use is to get hold of a DOM node for focusing, measuring or scrolling; the second is to store mutable data such as a timer id that plays no part in the render output. Because the container never causes a render, it is the right place for values that matter to the process but not to the screen.

GroupEffects & Performance
KindHook
SinceReact 16.8

ℹ️ 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 ref = useRef(initialValue)
ref.current          // read
ref.current = ...    // write: legal, but it does not trigger a render

<input ref={ref} />  // after it is mounted, ref.current is the node itself

⚙️ Parameters

initialValueThe initial value of current; it only takes effect on the first render, and changing the argument later does not reassign it.

Returns:Returns a stable { current: initialValue } object: it is the very same reference for the whole lifetime of the component.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

Clicking "Focus" jumps the caret into the input; clicking "Clear and focus" empties the field and puts the caret back — DOM work that state simply cannot do.

💡 Key Points

💡 Tip Use state for what the declarative style can do (rendering content) and a ref only for what must be imperative (focusing, scrolling, measuring).
ℹ️ Info Changing ref.current does not re-render — a ref is an escape hatch, so never keep data there that the UI depends on.
⚠️ Warning Reading or writing a ref during render breaks the pure-function contract (lazy initialization excepted); do ref work in event handlers or effects.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q What is the difference between a ref and state?
A A change in state triggers a re-render, a change in a ref does not; state is data for rendering, a ref is data for the process.
Q When does the initial value of ref.current take effect?
A When the ref is created on the first render; later re-renders never reset current because the argument changed.
Q Can I reach the DOM inside a child component?
A Not by default (a ref is not an ordinary prop). Forward it with forwardRef, or let the child expose an interface with useImperativeHandle.
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%

🙏 帮我们做得更好

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

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