AnimatePresence for Enter/Exit Transitions
You'll learn how to smoothly animate components as they leave the DOM using Framer Motion's AnimatePresence wrapper.
The Core Problem
By default, React removes components from the DOM instantly when they unmount. This makes exit animations impossible—the element is gone before any animation can play. It's like trying to watch someone walk out a door after they've already teleported away.
What AnimatePresence Does
AnimatePresence is a special wrapper component from Framer Motion that delays the removal of a component until its exit animation completes. Think of it as a polite doorman who holds the door open long enough for your component to gracefully exit the stage.
When you wrap conditionally rendered components with AnimatePresence, Framer Motion:
- Detects when a component is being unmounted
- Keeps it in the DOM temporarily
- Plays the exit animation you defined
- Finally removes it from the DOM
Basic Pattern
<AnimatePresence>
{isVisible && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
I fade in AND fade out!
</motion.div>
)}
</AnimatePresence>
Without AnimatePresence, the exit prop would be ignored—the component would just vanish. With it, you get the smooth fade-out before removal.
Essential Rules
- Only direct children of
AnimatePresencecan use exit animations - Each child must have a unique
keyprop if you're rendering multiple items - The component must be conditionally rendered (not just hidden with CSS)
Key Takeaway: AnimatePresence solves React's instant-unmount limitation by keeping components alive long enough to animate out gracefully—essential for professional-feeling UI transitions.