More React Hooks · Lesson 16 of 31
React useRef Hook
useRef gives a component a box – { current: … } – that keeps its contents between renders but doesn't trigger a re-render when you change it. It has two main jobs: holding a reference to a DOM element (to focus it, scroll to it or measure it) and remembering values such as timer IDs that the screen doesn't depend on.
In this lesson
- Accessing DOM elements: focus, scroll, measure
- Storing mutable values like interval IDs
- Refs vs state
- Passing a ref to your own component (React 19's
refprop)
Accessing a DOM element
import { useRef, useState } from "react";
export default function App() {
const inputRef = useRef(null); // { current: null } on the first render
const [items, setItems] = useState([]);
function handleAdd() {
const value = inputRef.current.value.trim(); // read the DOM input directly
if (value) setItems([...items, value]);
inputRef.current.value = "";
inputRef.current.focus(); // put the cursor back for the next item
console.log("focused:", document.activeElement === inputRef.current);
}
return (
<div>
<input ref={inputRef} aria-label="Item" /> {/* React sets inputRef.current to this element */}
<button onClick={handleAdd}>Add item</button>
<ul>{items.map((it) => <li key={it}>{it}</li>)}</ul>
</div>
);
}
[] [Add item] › type “Milk” into Item [Milk] [Add item] › click “Add item” [] [Add item] • Milk console: focused: true › type “Eggs” into Item [Eggs] [Add item] • Milk › click “Add item” [] [Add item] • Milk • Eggs console: focused: true
React fills ref.current with the DOM node after it renders the element, and sets it back to null when the element is removed. Only read or write ref.current in event handlers and effects – never during rendering.
Storing a value that isn't shown
A stopwatch needs the interval ID to stop it later. The ID never appears on screen, so it doesn't belong in state:
import { useRef, useState } from "react";
export default function App() {
const [ms, setMs] = useState(0);
const intervalRef = useRef(null);
function start() {
if (intervalRef.current) return; // already running
intervalRef.current = setInterval(() => setMs((t) => t + 100), 100);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
return (
<div>
<p>{(ms / 1000).toFixed(1)}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
<button onClick={() => { stop(); setMs(0); }}>Reset</button>
</div>
);
}
0.0s [Start] [Stop] [Reset] › click “Start” 0.0s [Start] [Stop] [Reset] › wait 550ms 0.5s [Start] [Stop] [Reset] › click “Stop” 0.5s [Start] [Stop] [Reset] › wait 300ms 0.5s [Start] [Stop] [Reset] › click “Reset” 0.0s [Start] [Stop] [Reset]
The time stops at 0.5s and stays there after the extra wait, because stop() found the right ID in the ref.
Refs vs state
import { useRef, useState } from "react";
export default function App() {
const [stateCount, setStateCount] = useState(0);
const refCount = useRef(0);
return (
<div>
<p>state: {stateCount} · ref: {refCount.current}</p>
<button onClick={() => { refCount.current += 1; }}>Ref +1</button>
<button onClick={() => setStateCount((c) => c + 1)}>State +1</button>
</div>
);
}
state: 0 · ref: 0 [Ref +1] [State +1] › click “Ref +1” state: 0 · ref: 0 [Ref +1] [State +1] › click “Ref +1” state: 0 · ref: 0 [Ref +1] [State +1] › click “State +1” state: 1 · ref: 2 [Ref +1] [State +1]
The ref did change twice, but the screen only caught up when a state change caused a render. (Reading ref.current during render like this is only for the demo – don't do it in real code.)
| useState | useRef | |
|---|---|---|
| Changing it re-renders? | yes | no |
| Value updates | on the next render (snapshot) | immediately (mutable) |
| Use for | anything shown on screen | DOM nodes, timer IDs, previous values, flags |
Passing a ref to your own component
In React 19, ref is a normal prop for function components – no more forwardRef:
import { useRef } from "react";
function SearchInput({ ref, label }) { // React 19: ref arrives as a prop
return <input ref={ref} aria-label={label} placeholder={label} />;
}
export default function App() {
const searchRef = useRef(null);
return (
<div>
<SearchInput ref={searchRef} label="Search the docs" />
<button onClick={() => { searchRef.current.value = "useRef"; searchRef.current.focus(); }}>
Try an example
</button>
</div>
);
}
[Search the docs…] [Try an example] › click “Try an example” [useRef] [Try an example]
Refs are an escape hatch
If you find yourself changing text, classes or visibility through ref.current, stop – that's React's job, and it will overwrite your changes on the next render. Use refs for things React doesn't manage: focus, scroll position, measuring, media playback and third-party widgets.
Practice
Try it yourself
Show the previous value of a counter next to the current one, using a ref updated in an effect.
Show solution
import { useEffect, useRef, useState } from "react"; export default function App() { const [count, setCount] = useState(5); const prevRef = useRef(null); useEffect(() => { prevRef.current = count; // runs after render, ready for the next one }, [count]); const prev = prevRef.current; return ( <div> <p>Now: {count}, before: {prev ?? "–"}</p> <button onClick={() => setCount((c) => c * 2)}>Double</button> </div> ); }Now: 5, before: – [Double] › click “Double” Now: 10, before: 5 [Double] › click “Double” Now: 20, before: 10 [Double]
This classic pattern reads a ref during render, which the React docs discourage. It's shown because interviewers still ask about it; in new code, store the previous value in state when you need it on screen.
Quick check
Does changing ref.current re-render the component?
No.
When is a DOM ref's current value set?
After React renders and attaches the element; it's null before that and after removal.
How do you pass a ref to your own component in React 19?
As a normal ref prop; forwardRef is no longer needed.
Summary
- useRef returns a mutable { current } box that survives renders without causing them.
- Use it for DOM access (focus, scroll, measure) and values like timer IDs.
- Read and write refs in handlers and effects, not during render; in React 19 ref is a prop.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.