Course contentsShow
← React
Lesson 705 of 2,39619. useRefFree lesson

Refs Survive Re-renders

The same ref object persists across all renders of a component, making it ideal for storing mutable values.

Refs Survive Re-renders

What you'll learn: How the same ref object persists across every render of your component, making it perfect for storing mutable values without triggering re-renders.

The Core Idea

When your component re-renders (whether from state changes, prop updates, or parent re-renders), React executes your component function from top to bottom again. Most variables get recreated with fresh values each time. But refs are different.

The ref object returned by useRef is created once and then persists for the entire lifetime of your component instance. Even though your component function runs repeatedly, useRef returns the same exact ref object every single time.

Why This Matters

This persistence is what makes refs useful for:

  • Storing values that need to survive across renders
  • Keeping mutable data that doesn't need to trigger re-renders
  • Maintaining references to DOM elements or timers

A Mental Model

Think of a ref like a box with a sticky note on your component. Every time React re-renders your component (like repainting a room), it throws away and recreates most things inside. But that box with the sticky note? React leaves it exactly where it is, untouched. You can peek inside the box (ref.current) or change what's inside anytime, and it'll still be there the next time React re-renders your component.

Unlike useState, updating ref.current doesn't cause a re-render. The ref just sits there quietly, preserving whatever value you put inside it, render after render after render.

Key Takeaway: The same ref object returned by useRef persists throughout all re-renders of your component, making it ideal for storing mutable values that don't need to trigger UI updates.