Lesson 3 of 11
useRef - DOM Access & Stable Values
useRef has two distinct use cases that share one API: (1) accessing DOM nodes directly, and (2) storing mutable values that persist across renders without causing re-renders. Understanding both is critical for animations, focus management, and stable interval/timeout tracking.
Two Use Cases of useRef
import { useRef, useEffect, useState } from 'react';
// USE CASE 1: DOM element reference
function AutoFocusInput() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus(); // safe optional chaining
}, []);
return <input ref={inputRef} placeholder="Auto-focused" />;
}
// USE CASE 2: Mutable value that survives re-renders without causing them
function Stopwatch() {
const [time, setTime] = useState(0);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
function start() {
if (intervalRef.current !== null) return; // already running
intervalRef.current = setInterval(() => {
setTime(t => t + 1);
}, 1000);
// intervalRef.current is mutable - changing it doesn't trigger re-render
}
function stop() {
if (intervalRef.current === null) return;
clearInterval(intervalRef.current);
intervalRef.current = null;
}
useEffect(() => () => stop(), []); // cleanup on unmount
return (
<div>
<p>{time}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}
// KEY DIFFERENCE:
// useState โ change causes re-render (use for UI-affecting data)
// useRef โ change does NOT cause re-render (use for non-UI data, DOM refs)Storing Previous Values & forwardRef
// Storing previous prop/state value
function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => {
ref.current = value; // update AFTER render
});
return ref.current; // returns value from PREVIOUS render
}
function AnimatedCounter({ count }: { count: number }) {
const prevCount = usePrevious(count);
const direction = count > (prevCount ?? 0) ? 'โ' : 'โ';
return <span>{direction} {count}</span>;
}
// forwardRef - expose a child component's DOM node to a parent
import { forwardRef } from 'react';
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label: string;
}
// forwardRef passes the parent's ref through to the internal DOM element
const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, ...rest }, ref) => (
<label>
{label}
<input ref={ref} {...rest} />
</label>
)
);
Input.displayName = 'Input'; // needed for devtools
// Parent can now focus the input inside the child component
function Form() {
const emailRef = useRef<HTMLInputElement>(null);
return (
<>
<Input ref={emailRef} label="Email" type="email" />
<button onClick={() => emailRef.current?.focus()}>Focus Email</button>
</>
);
}Common Mistakes - useRef
- Reading `ref.current` during render (outside useEffect) - `ref.current` is null until after the first commit; read it in useEffect or event handlers only
- Using useRef for state that affects the UI - ref changes are invisible to React; if a value change should update the display, use useState
- Expecting useRef to trigger re-renders - it won't; if you need to react to a ref change, combine with a state update: set state after updating the ref
- Not using optional chaining on ref.current - always use `ref.current?.method()` since ref.current is null before mount and after unmount
Tip
Tip
Practice useRef DOM Access Stable Values in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for useRef - DOM Access & Stable Values
Practice Task
Note
Practice Task - (1) Write a working example of useRef DOM Access Stable Values from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with useRef DOM Access Stable Values is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- useRef has two distinct use cases that share one API: (1) accessing DOM nodes directly, and (2) storing mutable values that persist across renders without causing re-renders.
- Reading `ref.current` during render (outside useEffect) - `ref.current` is null until after the first commit; read it in useEffect or event handlers only
- Using useRef for state that affects the UI - ref changes are invisible to React; if a value change should update the display, use useState
- Expecting useRef to trigger re-renders - it won't; if you need to react to a ref change, combine with a state update: set state after updating the ref
Finished this lesson?