Keys in AnimatePresence
What you'll learn: How React keys help AnimatePresence track which specific component is entering or exiting the DOM.
Why AnimatePresence Needs Unique Keys
When you conditionally render components inside AnimatePresence, React needs a way to distinguish between different component instances. Without unique keys, React can't tell if you've replaced one component with another or simply updated the same component.
AnimatePresence relies on React's reconciliation algorithm. When a component's key changes, React treats it as a completely different component—triggering an unmount of the old one and a mount of the new one. This is exactly what AnimatePresence needs to run exit animations on the old component while simultaneously running enter animations on the new one.
The Problem Without Keys
Imagine rendering different images based on state. If you don't provide keys, React sees the same <motion.img> element and updates its src attribute in place—no unmount occurs, so no exit animation runs. The image just suddenly changes.
// ❌ No exit animation — React updates in place
<AnimatePresence>
{showCat && <motion.img src="cat.jpg" exit={{ opacity: 0 }} />}
</AnimatePresence>
The Solution: Unique Keys
By adding a unique key, you tell React these are different components:
// ✅ Exit animation runs — React sees two distinct components
<AnimatePresence>
{showCat ? (
<motion.img key="cat" src="cat.jpg" exit={{ opacity: 0 }} />
) : (
<motion.img key="dog" src="dog.jpg" exit={{ opacity: 0 }} />
)}
</AnimatePresence>
Now when you toggle between cat and dog, AnimatePresence detects the key change, keeps the old component mounted long enough to animate out, and simultaneously animates the new one in.
Key Takeaway: Unique keys are AnimatePresence's tracking mechanism—without them, React treats your components as updates rather than replacements, preventing exit animations from running.