useRef — the DOM and persistent values
2 min read
When you need to reach a DOM element directly
Usually in React you change the UI through state — not by touching the DOM. But sometimes you genuinely need the actual element: to focus an input, play a video, or measure size. For that, React gives you useRef.
Referencing a DOM element
import { useRef } from "react";
function SearchBox() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus(); // reach the real input
}
return (
<div>
<input ref={inputRef} placeholder="Search..." />
<button onClick={focusInput}>Focus the box</button>
</div>
);
}
Three steps:
- Create a ref:
const inputRef = useRef(null). - Attach it:
<input ref={inputRef} />. - Use it:
inputRef.currentis now the real DOM element — soinputRef.current.focus()focuses it.
The other use: remembering a value without re-rendering
A ref can also store any value that survives re-renders — like state, but with one big difference: changing a ref does NOT cause a re-render.
const countRef = useRef(0);
countRef.current = countRef.current + 1; // no re-render
Use this for values you want to remember but that should not affect the screen — like a timer id, or a previous value.
useRef vs useState — when to use which?
- Need the value shown on screen? →
useState(it re-renders). - Just need to remember something, or touch the DOM, without re-rendering? →
useRef.
useRefgives you a.currentbox. Attach it to an element to reach the real DOM (e.g..focus()), or use it to remember a value across renders without triggering a re-render.