Common AnimatePresence Pitfalls
You'll learn: The most frequent mistakes developers make when using Framer Motion's AnimatePresence, and how to avoid broken or missing animations.
The Missing Keys Problem
AnimatePresence relies on React keys to track which components are entering or exiting. Without unique keys, React can't distinguish between different instances, and exit animations won't fire.
// ❌ Missing key — exit animation won't work
<AnimatePresence>
{isVisible && <motion.div exit={{ opacity: 0 }}>Item</motion.div>}
</AnimatePresence>
// ✅ Always add a key
<AnimatePresence>
{isVisible && <motion.div key="item" exit={{ opacity: 0 }}>Item</motion.div>}
</AnimatePresence>
Think of keys like name tags at a party—without them, you can't tell when someone specific leaves.
Multiple Children Without Fragments
AnimatePresence expects direct children to be animatable components. If you render multiple siblings without wrapping them, only the first child is tracked.
// ❌ Multiple direct children confuse AnimatePresence
<AnimatePresence>
{showA && <motion.div key="a">A</motion.div>}
{showB && <motion.div key="b">B</motion.div>}
</AnimatePresence>
// ✅ Wrap in a fragment or use mode="wait" for single-item animations
<AnimatePresence mode="wait">
{showA ? <motion.div key="a">A</motion.div> : <motion.div key="b">B</motion.div>}
</AnimatePresence>
AnimatePresence Placement Too High
Placing AnimatePresence far from the conditional rendering can break tracking, especially if intermediate components don't preserve keys.
// ❌ Too far from the actual conditional
<AnimatePresence>
<Layout>
<Sidebar />
{isVisible && <motion.div>Content</motion.div>}
</Layout>
</AnimatePresence>
// ✅ Wrap closely around the conditional content
<Layout>
<Sidebar />
<AnimatePresence>
{isVisible && <motion.div key="content">Content</motion.div>}
</AnimatePresence>
</Layout>
Key Takeaway: Always add explicit keys to conditional components, keep AnimatePresence close to the conditional logic, and use fragments or mode appropriately for multiple children.