Capítulo 34 de 116
useRef gives a component a mutable "box" ({ current: value }) that persists across renders like state, but changing it does not trigger a re-render and reading/writing it doesn't follow the snapshot rules from Ch 23 — use it for values a component needs to remember that shouldn't affect what's on screen.
const ref = useRef(initialValue): returns a plain object with one mutable property, ref.current, initialized to initialValue. That object identity stays stable across the component's entire lifetime.useState's setter queues a re-render; mutating ref.current does not re-render at all. State follows the snapshot model (Ch 23, fixed within a render); ref.current is a live, mutable value you can read and write mid-render or in a handler without waiting for the next render.ref.current during rendering (only in event handlers or Effects) — since ref changes aren't tracked, reading one during render makes the component's output unpredictable, defeating the purity model from Ch 18.ref attribute makes React populate ref.current with the actual underlying DOM node once mounted — the mechanism explored fully in Ch 35.function StopwatchButtons() {
const intervalRef = useRef(null); // survives renders, doesn't cause them
function handleStart() {
intervalRef.current = setInterval(() => { /* tick */ }, 1000);
}
function handleStop() {
clearInterval(intervalRef.current);
}
return <>{/* buttons calling handleStart/handleStop */}</>;
}
ref.current during the render body itself — confine ref access to event handlers and Effects, keeping rendering pure.