Build exit animations like AnimatePresence: keep removed children mounted, usePresence, re-entry and wait mode
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
- 4
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1React unmounts a child the moment it leaves the children you render. To animate it out,
Presencemust keep rendering something React no longer gives it. What does it need to remember from the previous render?
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.