React Reference ยท Effect and Ref Hooks
React useRef with DOM nodes
Learn how to use useRef to reach DOM elements in React: focus inputs, measure sizes, keep lists of nodes with ref callbacks, and avoid common mistakes.
Most of the time React updates the DOM for you. For the few jobs it does not cover (focusing an input, selecting text, measuring an element, starting a video) you need the real DOM node. Create a ref with useRef, pass it to the ref prop of a built-in element, and after the commit ref.current is that node.
React sets current to the node when the element is added to the page and back to null when it is removed. Use the node inside event handlers and effects, not while rendering.
const inputRef = useRef(null); // ... <input ref={inputRef} /> // later: inputRef.current.focus()
Try it
A list needs one node per item, and you cannot call a hook in a loop. Pass a function to ref instead (a ref callback) and store the nodes in a Map that lives in one ref.
Syntax
const ref = useRef(null); <element ref={ref} /> // ref object <element ref={(node) => { ... }} /> // ref callback (React 19: may return a cleanup function)
| Name | Description |
|---|---|
ref (object) |
Receives the DOM node in ref.current after commit, and null after the element is removed. |
ref (function) |
Called with the node when attached. In React 19 it may return a cleanup function, which runs on detach instead of a call with null. |
Returns: the node is an instance of the matching DOM interface (HTMLInputElement, HTMLDivElement, ...).
Usage notes
- Start with
null. Until the first commit there is no node, so guard withref.current?.focus()if the code can run early. - Use refs for what React cannot express: focus, text selection, scrolling, measuring, imperative media control (
play()), and integrating non-React libraries. - Do not edit React-managed DOM (adding or removing children, changing text of elements React renders). React will not know and can crash on the next update. Reading, focusing and measuring are safe.
- Custom components. In React 19 a function component receives
refas a prop and can forward it; see ref as a prop. In older versions useforwardRef. - Ref callbacks in React 18 are called with
nullon detach; in React 19 returning a cleanup function opts into the new behavior. An inline arrow function is a new function on every render, so React detaches and re-attaches it each time; that is fine for the Map pattern above because it is idempotent. - Conditional elements: a ref on an element that is not rendered stays
null. - Flushing first: if you set state and need the DOM updated before you read it, wrap the update in
flushSync.