React Reference ยท Effect and Ref Hooks
React useRef hook
Reference for React useRef: keep a mutable value that survives re-renders without causing one, with examples, rules and common mistakes.
useRef returns a plain object with a single property, current, that React keeps the same between renders. Changing ref.current does not trigger a re-render. That makes a ref the right home for values that matter to your code but not to the screen: timer ids, the previous value of a prop, a flag that says "already ran", or a handle to a DOM node.
The same hook is used for DOM access; that side of it has its own page, useRef with DOM nodes.
const countRef = useRef(0); countRef.current += 1; // no re-render
Try it
Bump the ref three times: the console updates but the screen does not. Then bump the state and the screen catches up on both values.
Syntax
const ref = useRef(initialValue); // TypeScript: useRef<T>(initialValue: T): RefObject<T>
| Name | Description |
|---|---|
initialValue |
The starting value of ref.current. It is used only on the first render and ignored afterwards. |
Returns: an object { current: initialValue } that is the same object on every render of the same component instance.
Edge cases: assigning a ref to a JSX element (<div ref={ref}>) makes React overwrite current with the DOM node on mount and set it to null on unmount.
Usage notes
- Do not read or write
ref.currentduring render (except to initialize it). Render must stay pure; reading a ref makes the output depend on something React cannot track. Read and write refs in event handlers and effects. - Lazy initialization pattern.
useRef(new Expensive())callsnew Expensive()on every render, even though the result is discarded. Instead writeif (ref.current === null) ref.current = new Expensive();right after the hook; this one-time write during render is allowed. - Changing a ref does not re-render. If a value must show up on screen, use
useState. - Refs survive as long as the component instance does. A different
keyor unmounting creates a new ref. - Previous value pattern: a ref updated in an effect holds the value from the last committed render, as shown above.
- Strict Mode: in development React renders twice; refs created in render are discarded from the first pass, so do not rely on side effects there.
- React 19 passes
refas an ordinary prop to function components, see ref as a prop.