Course contentsShow
← React
Lesson 1981 of 2,39645. AnimationsFree lesson

Conditional Rendering with AnimatePresence

Master wrapping conditional components in AnimatePresence to animate their appearance and disappearance smoothly.

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:

  1. Detects the removal
  2. Keeps the component mounted temporarily
  3. Triggers the exit animation
  4. 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.