useRef creates a persistent reference that survives renders. It is commonly used for DOM elements and mutable values that should not themselves cause a re-render.
1 Basic Syntax
const valueRef = useRef(0);
valueRef.current = 10;
Changing current does not cause a re-render.
2 DOM Reference
function SearchBox() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</div>
);
}
3 Ref Flow
flowchart TD
A[Create Ref] --> B[Attach Ref To DOM]
B --> C[React Sets Current]
C --> D[Event Or Effect]
D --> E[Use Current Value]
4 Previous Value
function User({ userId }) {
const previousId = useRef(userId);
useEffect(() => {
console.log("Previous:", previousId.current);
previousId.current = userId;
}, [userId]);
return <p>Current: {userId}</p>;
}
5 Timer ID
const timerRef = useRef(null);
function start() {
timerRef.current = setInterval(() => console.log("Tick"), 1000);
}
function stop() {
clearInterval(timerRef.current);
}
6 useRef vs useState
| useState | useRef |
|---|---|
| Used for rendered state | Used for persistent mutable references |
| Setter causes re-render | Changing current does not re-render |
| Good for UI state | Good for DOM refs and timers |
7 Stopwatch Example
function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
function start() {
if (intervalRef.current) return;
intervalRef.current = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
useEffect(() => () => clearInterval(intervalRef.current), []);
return (
<div>
<h2>{seconds}</h2>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}
8 Common Mistakes
- Using useRef when the value must update the UI.
- Expecting current changes to render again.
- Reading a DOM ref before mounting.
- Forgetting timer cleanup.
- Using refs as a replacement for state.
9 Interview Questions
- What is useRef?
- Does changing current cause a render?
- How do you access a DOM element?
- When should useRef be used instead of useState?
- How can useRef store a previous value?
10 Key Takeaways
- useRef provides a persistent current value.
- DOM elements can be referenced with refs.
- Ref changes do not cause rendering.
- Refs are useful for timers and imperative DOM operations.
Conclusion
Think of useRef as a persistent box React keeps between renders. Use it when you need to remember something without making that change part of the rendered UI.