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

onTransitionEnd for Cleanup Logic

Listen to transitionend events to remove elements from the DOM after animations complete.

onTransitionEnd for Cleanup Logic

What you'll learn: How to listen for transition completion events to safely remove elements from the DOM after their exit animations finish.

The Problem with Immediate Removal

When you conditionally render components with {isVisible && <Component />}, React immediately removes them from the DOM when isVisible becomes false. This doesn't give CSS transitions time to complete—the fade-out or slide animation gets cut short.

The onTransitionEnd Event

The onTransitionEnd event fires when a CSS transition completes. This is your signal that an animation has finished and it's safe to perform cleanup operations like removing the element from the DOM.

How it works:

  1. When hiding an element, don't remove it immediately—just add a CSS class that triggers the exit animation
  2. Listen for the onTransitionEnd event on that element
  3. In the handler, then remove the element from state/DOM
function Modal({ isOpen, onClose }) {
  const [shouldRender, setShouldRender] = useState(isOpen);
  const [isAnimating, setIsAnimating] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setShouldRender(true);
    } else {
      setIsAnimating(true); // Trigger exit animation
    }
  }, [isOpen]);

  const handleTransitionEnd = () => {
    if (isAnimating) {
      setShouldRender(false); // Now safe to remove
      setIsAnimating(false);
    }
  };

  if (!shouldRender) return null;

  return (
    <div
      className={`modal ${isAnimating ? 'modal-exit' : 'modal-enter'}`}
      onTransitionEnd={handleTransitionEnd}
    >
      {/* Modal content */}
    </div>
  );
}

Think of it like a theater curtain: You don't yank it down mid-close—you wait for the curtain to fully descend before the stagehands remove the set.

Key Takeaway: Use onTransitionEnd to delay DOM removal until after CSS transitions complete, ensuring smooth exit animations without visual glitches.