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

AnimatePresence for Enter/Exit Animations

Learn how AnimatePresence enables exit animations by keeping removed components mounted until their animation completes.

AnimatePresence for Enter/Exit Animations

You'll learn how AnimatePresence solves the "disappearing element" problem by keeping removed components alive long enough to animate out.

The Problem with Exit Animations

When React unmounts a component (conditional rendering flips to false), the element vanishes from the DOM immediately. There's nothing to animate — it's already gone. This is why CSS transitions can handle hover/focus, but struggle with mount/unmount.

How AnimatePresence Works

AnimatePresence wraps conditionally rendered motion components and keeps them in the DOM until their exit animation finishes. Think of it like a stagehand who waits for an actor to walk offstage before removing the set piece, rather than yanking it away mid-performance.

import { AnimatePresence, motion } from 'framer-motion';

function Modal({ isOpen, onClose }) {
  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.8 }}
          className="modal"
        >
          <button onClick={onClose}>Close</button>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

The exit prop defines the animation that plays before React removes the component. Without AnimatePresence, that exit animation would never run.

Key Details

  • Wrap conditional content: AnimatePresence must be the parent of conditionally rendered motion elements
  • Direct children: Each child needs a unique key prop if you're animating lists
  • Exit animations run automatically: When the condition becomes false, the exit animation plays, then React unmounts

Key Takeaway: AnimatePresence delays unmounting until exit animations complete, enabling smooth disappearances that would otherwise be impossible with React's instant removal.