What useRef is: A Mutable Box
You'll learn: What useRef actually is and why it doesn't cause re-renders like useState does.
The Core Idea
useRef returns a plain JavaScript object with a single property: .current. That's it. Think of it as a box you can put any value into, and that box persists across renders. Unlike useState, changing what's inside the box doesn't trigger a re-render.
const myRef = useRef(initialValue);
// myRef is now: { current: initialValue }
myRef.current = "new value"; // Mutate freely, no re-render
The Mutable Box Analogy
Imagine you have a shoebox on your desk that never moves. You can:
- Put something in it (
myRef.current = value) - Check what's inside (
const value = myRef.current) - Replace what's inside anytime you want
- The box stays in the same spot (same object reference) forever
React gives you the same box object every single render. You're not getting a new box—you're getting the exact same one.
Why No Re-renders?
When you call setState, React says "whoa, something changed, better re-render to show the user!" But when you mutate myRef.current, React says nothing. It's just a property change on a regular JavaScript object. React isn't watching it.
This makes refs perfect for storing values you need to remember but don't need to display:
- Timer IDs
- Previous values
- Animation frame IDs
- Values you'll read in event handlers or effects
Key Takeaway: useRef gives you a persistent, mutable object that survives re-renders without causing them—it's React's way of letting you keep a "side note" that doesn't affect rendering.