Conditional Rendering with AnimatePresence
What you'll learn: How to wrap conditionally-rendered components in AnimatePresence so they animate smoothly both when they appear and when they disappear.
The Problem AnimatePresence Solves
When you conditionally render a component in React ({isOpen && <Modal />}), React immediately removes it from the DOM when the condition becomes false. This happens instantly—before any exit animation can play. AnimatePresence solves this by keeping the component mounted just long enough for its exit animation to complete.
Think of it like a stage manager for your components: when an actor (component) needs to leave the stage, AnimatePresence holds the curtain open until they finish their exit performance, then removes them gracefully.
The Basic Pattern
Wrap your conditional rendering in <AnimatePresence>:
import { motion, AnimatePresence } from 'framer-motion';
function App() {
const [isVisible, setIsVisible] = useState(false);
return (
<>
<button onClick={() => setIsVisible(!isVisible)}>
Toggle
</button>
<AnimatePresence>
{isVisible && (
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 20 }}
>
I animate in AND out!
</motion.div>
)}
</AnimatePresence>
</>
);
}
How It Works
AnimatePresence monitors its children. When a child is removed from the conditional (like when isVisible becomes false), it:
- Detects the removal
- Keeps the component mounted temporarily
- Triggers the
exitanimation - Actually unmounts the component once the animation finishes
Key Takeaway: Wrap conditional motion components in <AnimatePresence> to enable exit animations—it delays unmounting until the exit prop animation completes, creating smooth disappearance effects.