Build exit animations like AnimatePresence: keep removed children mounted, usePresence, re-entry and wait mode

hardAbout 60 minutesUpdated CodingProreactanimationframer-motionchildrenreconciliationcontext
Not solved

Share this question

Problem

Removing an element from a React list unmounts it straight away, so there is nothing left to animate out. Libraries like Framer Motion solve this with AnimatePresence: removed children stay mounted, learn that they are leaving, run their exit animation, and then say they are done. The hard parts are ordering (where does a leaving item sit among new ones?), items that come back while they are leaving, and nested components that all animate. Build it.

function Toast({ text }) {
  const [isPresent, safeToRemove] = usePresence();
  useEffect(() => {
    if (!isPresent) setTimeout(safeToRemove, 300); // after the fade-out
  }, [isPresent, safeToRemove]);
  return <li style={{ opacity: isPresent ? 1 : 0 }}>{text}</li>;
}

<Presence>{toasts.map((t) => <Toast key={t.id} text={t.text} />)}</Presence>

Ref. UR-1437 · © UIRound · uiround.com/questions/build-exit-animations-like-animatepresence-keep-removed-children-mounted-usepresence-re-entry-and-wait-mode

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment