Presence is a component that helps you animate elements in and out of the DOM. It keeps elements mounted during exit animations and provides a present state to child components, enabling smooth mount and unmount animations.
Installation
Component
Presence
Props
boolean
required
Whether the component should be present (mounted) in the DOM. When
false, the component remains mounted until exit animations complete.React.ReactElement | ((props: { present: boolean }) => React.ReactElement)
required
The element to animate. Can be a React element or a render function that receives
present state.Usage
Basic Fade Animation
Using Render Function
Slide Animation
Scale Animation
Multiple Animations
Conditional Content Based on State
How It Works
Presence uses a state machine with three states:
- mounted: Component is present and visible
- unmountSuspended: Component is animating out (exit animation)
- unmounted: Component is removed from DOM
State Transitions
- When
presentchanges fromfalsetotrue:unmounted→mounted - When
presentchanges fromtruetofalse:- If CSS animation detected:
mounted→unmountSuspended - When animation ends:
unmountSuspended→unmounted - If no animation:
mounted→unmounted(immediate)
- If CSS animation detected:
Animation Detection
The component:- Reads computed styles to detect CSS animations
- Listens to
animationend,animationcancel, andanimationstartevents - Waits for animations to complete before unmounting
- Handles animation interruptions (e.g., when
presentchanges mid-animation)
Important Notes
The component detects CSS animations by reading the
animation-name computed style. Make sure your exit animations have a different animation-name than entry animations.If the element has
display: none or no animation defined, it will unmount immediately when present becomes false.The component uses
useLayoutEffect to synchronously detect animation changes before the browser paints, preventing flashing.When using the render function pattern, the
present prop lets you conditionally render content or apply different styles during entry and exit.Best Practices
- Always define exit animations - Without them, the component unmounts immediately
- Use different animation names - Entry and exit animations should have distinct names
- Set animation-fill-mode - The component sets
forwardsduring exit to prevent flashing - Test animation timing - Ensure animations complete before state changes occur
Browser Compatibility
The component relies on:- CSS Animations API
getComputedStyle()- Animation events (
animationend,animationcancel,animationstart)