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:
- The old component instance unmounts, destroying its DOM elements
ref.currentbecomesnullbecause the element no longer exists- A new component instance mounts with a fresh ref initialized to
null - 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.