AnimatePresence for Exit Animations
What you'll learn: How to animate components smoothly as they leave the React tree using Framer Motion's AnimatePresence wrapper.
React typically removes components instantly when they unmount, giving you no opportunity to animate their exit. AnimatePresence solves this by keeping components in the DOM long enough to complete their exit animations before final removal.
The Core Problem
When a component's conditional renders false, React unmounts it immediately. Without AnimatePresence, your carefully crafted exit animation defined in your motion component never gets a chance to run—the element simply vanishes.
How AnimatePresence Works
Wrap conditional motion components with <AnimatePresence>. When a child component is removed from the tree, AnimatePresence detects it and delays unmounting until the exit animation completes.
Think of it like a stage manager: Instead of yanking actors off stage mid-scene, the manager waits for them to finish their exit performance before closing the curtain.
Basic Pattern
import { motion, AnimatePresence } from 'framer-motion';
function Modal({ isOpen }) {
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
Modal content
</motion.div>
)}
</AnimatePresence>
);
}
When isOpen becomes false, the motion.div doesn't disappear instantly—it fades out via the exit animation first.
Critical Requirements
Each child must have a unique key prop when rendering lists, allowing AnimatePresence to track which specific items are entering or leaving.
Key Takeaway: AnimatePresence enables exit animations by temporarily keeping unmounting components in the DOM until their exit animation completes, making component removal feel smooth and intentional rather than abrupt.