AnimatePresence
Animate components when they're removed from the React tree.
AnimatePresence
allows components to animate out when they're removed from the React tree.
It's required to enable exit animations because React lacks a lifecycle method that:
Notifies components when they're going to be unmounted and
Allows them to defer that unmounting until after an operation is complete (for instance an animation).
Usage
Exit animations
AnimatePresence
works by detecting when direct children are removed from the React tree.
Any motion
components contained by the removed child that have an exit
prop will fire that animation before the entire tree is finally removed from the DOM.
Note: Direct children must each have a unique key
prop so AnimatePresence
can track their presence in the tree.
Like initial
and animate
, exit
can be defined either as a TargetAndTransition
object of values, or a variant label to animate out a whole tree.
In React, changing a component's key
makes React treat it as an entirely new component. So the old one is unmounted before the new one is mounted. So by changing the key
of a single child of AnimatePresence
, we can easily make components like slideshows.
Multiple children
AnimatePresence
works the same way with multiple children. Just ensure that each has a unique key
and components will animate in and out as they're added or removed from the tree.
Suppressing initial animations
Mount animations are already handled by motion
components via the initial
and animate
props.
If a motion
component is set to initial={false}
, it'll start in the state defined in animate
. But sometimes, for instance a chatbox or a slideshow, we only want to animate in new components, that are added after the initial render.
By setting initial={false}
on AnimatePresence
, components present when AnimatePresence
first loads will start in their animate
state. Only components that enter after this initial render will animate in.
Animating custom components
The children of AnimatePresence
can also be custom components. The only requirement is that somewhere within this component is at least one motion
component with an exit
prop.
Note: The custom component being removed from the DOM must still be a direct descendant of AnimatePresence
for the exit
animation(s) it contains to trigger.