React useRef

useRef provides a stable mutable object whose changes do not trigger component re-renders. It is commonly used to retain a value across renders or to access a DOM element without putting that value in rendered state.

`useRef(initialValue)` returns an object with a `current` property. React keeps the same ref object for the component instance across renders, so changing `ref.current` does not itself cause another render.

A common use is referencing a DOM node. Pass the ref to an element such as `<input `, then access the mounted element through `inputRef.current`, typically inside an event handler or effect.

Refs can also hold mutable values that should survive renders but do not belong in the UI. Examples include timer IDs, previous values, or an imperative library instance. Unlike state, updating `ref.current` is not a request for React to render again.

Because React does not track changes to `current` for rendering, a ref should not replace state when the value needs to appear in the UI. If a value changes and the component must reflect that change, use state instead.

Key points

Interview questions

How do you use useRef to access an input element?

Create a ref with `useRef(null)` and pass it to the input's `ref` prop. After the element mounts, React assigns the DOM node to `inputRef.current`. Code such as an event handler or effect can then call DOM methods through that reference, for example `inputRef.current.focus()`.

When should you use useRef instead of useState?

Use a ref when a value must persist between renders but changing that value should not itself update the UI. Use state when a value participates in rendering and changes need to cause React to update the component. For example, a timer ID can live in a ref, while the elapsed time displayed to the user belongs in state.

Does useRef preserve its value between renders?

Yes. React returns the same ref object on subsequent renders of the same component instance. Its `current` property therefore retains the value assigned to it until the code changes it or the component instance is discarded. A new component instance gets its own ref.

What does useRef return, and why doesn't changing it cause a re-render?

`useRef` returns a stable object containing a `current` property. React preserves that object across renders for the component instance. Assigning a new value to `current` is just a mutation of that object, not a state update, so React does not schedule a render because of it.

Why is using a ref for a value rendered in JSX usually a mistake?

React does not automatically render again when `ref.current` changes. Therefore, changing the ref alone can leave the UI showing an old value. If the UI must respond to the change, state provides the update mechanism that is missing from a ref.