useTransition for Mounting/Unmounting
You'll learn how React Spring's useTransition hook gracefully animates components entering and leaving the DOM in dynamic lists.
What Is useTransition?
useTransition is React Spring's solution for animating components that mount (appear) and unmount (disappear) from your UI. Unlike useSpring which animates existing elements, useTransition handles the lifecycle of items coming and going — perfect for lists where items are added or removed dynamically.
Think of it like a stage director: when actors enter, they walk on smoothly; when they exit, they gracefully bow and leave rather than just vanishing.
Core Usage Pattern
You provide useTransition with three key pieces:
- Your data array — the items currently in your list
- Configuration object — how to track items and what animations to use
- Keys — unique identifiers to track which items are which
The hook returns a function that maps over transitions, giving you the animated style and the item data for each element in enter, update, or exit phase.
const transitions = useTransition(items, {
keys: item => item.id,
from: { opacity: 0, transform: 'translateY(-20px)' },
enter: { opacity: 1, transform: 'translateY(0px)' },
leave: { opacity: 0, transform: 'translateY(20px)' }
});
return transitions((style, item) => (
<animated.div style={style}>
{item.text}
</animated.div>
));
When you add an item, it animates from → enter. When removed, it animates leave before unmounting. Items already present can also animate on update.
Key Takeaway: useTransition orchestrates smooth enter/exit animations for dynamic lists by managing mounting and unmounting phases with spring-based physics, preventing jarring appearance/disappearance of UI elements.