Course contentsShow
← React
Lesson 1272 of 2,39632. Lists and Keys Deep DiveFree lesson

Stale Refs After Key Changes

How ref.current becomes null or points to wrong elements when components remount due to key changes.

Stale Refs After Key Changes

You'll learn how changing keys can cause refs to unexpectedly point to null or the wrong DOM element.

The Problem

When you use useRef to hold a reference to a DOM element, that reference remains stable within a component's lifecycle. But here's the catch: when a component's key changes, React unmounts the old component instance and mounts a completely new one. Your ref doesn't follow along—it still points to the old, now-destroyed element.

Think of it like having a business card with someone's office number. If they move to a new office (remount with a new key), your card still has their old office number. The reference hasn't updated automatically.

What Happens

When a key change triggers a remount:

  1. The old component instance unmounts, destroying its DOM elements
  2. ref.current becomes null because the element no longer exists
  3. A new component instance mounts with a fresh ref initialized to null
  4. The ref eventually points to the new element, but any external code holding the old ref is now stale

This breaks code that:

  • Stores refs in parent state or context
  • Passes refs to siblings expecting persistent access
  • Uses refs in event handlers from previous renders
  • Relies on refs in async operations or timeouts

Why It Matters

If you're managing focus, scroll position, or measurements with refs, key changes will silently break your logic. The ref appears to work until the key changes, then suddenly your .focus() call fails or your scroll calculation targets nothing.

Key Takeaway: Refs don't survive component remounts caused by key changes—they reset to null and create new references, breaking any external code expecting stability.