Common Use Case: Storing Previous Values
You'll learn how to use a ref to "remember" what a value was in the previous render — something state can't do.
The Problem
Sometimes you need to compare the current value of a prop or state to what it was last time the component rendered. Maybe you want to detect when a value increases, or log what changed. State can't help here — updating state triggers a re-render, and by then you've lost the old value.
The Ref Solution
A ref is perfect for this because:
- It persists across renders (survives re-renders)
- Updating
ref.currentdoesn't cause re-renders - You can update it after render using
useEffect
The Pattern
function Component({ count }) {
const prevCountRef = useRef();
useEffect(() => {
// After render, store current value for next time
prevCountRef.current = count;
});
const prevCount = prevCountRef.current;
return (
<div>
<p>Now: {count}, Before: {prevCount}</p>
</div>
);
}
How it works: On the first render, prevCountRef.current is undefined. After rendering, the effect runs and stores the current count. On the next render, you can read that stored value — it's the previous one! Then the effect runs again, updating it for next time.
Think of It Like This
Imagine writing today's date on a sticky note at the end of each day. Tomorrow, when you look at the note, you see yesterday's date. That's what the ref does — it holds yesterday's value.
Key Takeaway: Use a ref combined with useEffect to remember previous values: read ref.current during render, then update it in an effect after render.