When a user deletes a row from a table and the row simply vanishes, they lose the thread of what just happened. Animation in React is not decoration, it is the feedback channel that tells people which object changed, where it went, and whether the app registered their input at all. The real engineering question is never whether to animate. It is where the animation should run, because that single decision determines how much code you write, how much CPU you spend on the main thread, and which classes of bug you will be debugging three sprints later.
đĄThe rule of thumb
If the element already exists in the DOM and only its numbers change, CSS can animate it. If React is about to add or remove the element from the tree, you need a library that can hold the node open for the duration of the exit.
Where animation work actually runs
There are two engines available to you. The browser's own CSS transition and animation machinery runs on the compositor for transform and opacity, which means a moving card does not trigger layout, does not trigger paint, and generally costs a fraction of a millisecond per frame. JavaScript animation runs your timing function in the React world: it can read component state, decide that an item should slide left because it was archived rather than deleted, and coordinate several elements so they move in sequence.
The trade-off is lifecycle knowledge. CSS knows nothing about React. When a state update removes an element, React drops the node from the DOM in the same commit, so a CSS transition that would have animated opacity from one to zero never receives a starting frame. The element is gone before the browser ever computes a style. JavaScript libraries solve this by keeping the node mounted until the animation finishes, then telling React it is safe to unmount. That single trick is the entire reason React Transition Group and Framer Motion exist.
CSS transitions when the element stays mounted
Most of the animation in a real product is state that persists: a button that changes color on hover, a sidebar that slides open, a toast that rises from the corner. These elements are always mounted, they only change class, and CSS is the correct tool. The component below toggles a status class and lets the browser interpolate everything.
import { useEffect, useState } from 'react';
function Toast({ message, onDone, duration = 4000 }) {
const [visible, setVisible] = useState(false);
useEffect(() => {
const t1 = setTimeout(() => setVisible(true), 20);
const t2 = setTimeout(() => setVisible(false), duration);
const done = setTimeout(onDone, duration + 350);
return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(done); };
}, [duration, onDone]);
return (
<div className={visible ? 'toast toast--in' : 'toast toast--out'} role="status">
{message}
<button onClick={() => setVisible(false)} aria-label="Dismiss">
Dismiss
</button>
</div>
);
}
.toast {
transition: transform 320ms cubic-bezier(0.2, 0.9, 0.3, 1), opacity 320ms ease;
will-change: transform, opacity;
}
.toast--in { transform: translateY(0); opacity: 1; }
.toast--out { transform: translateY(16px); opacity: 0; }
Two details decide whether this feels professional. First, animate transform and opacity only, because those properties are handled without re-running layout; transitioning top, height or margin forces the browser to reflow every frame and produces visible jank on slower laptops. Second, stagger the timers rather than firing the removal immediately: the exit finishes roughly 350 ms after the state flips, so the unmount timeout must clear after the transition, not before it.
The exit problem, and why libraries exist
Enter animation is easy because React mounts the node, the browser lays it out with initial styles, and the next frame applies the target styles. Exit animation is the opposite: React removes the node in the same tick as the state change, so there is nothing left to animate. Teams usually discover this the first time they build a modal that disappears instantly despite a perfectly written transition.
React Transition Group solves it by rendering an extra state around your child. It keeps the element mounted during a leave phase, fires a callback when the transition ends, and only then lets the parent re-render without it.
import { CSSTransition, TransitionGroup } from 'react-transition-group';
function Inbox({ items, onArchive }) {
return (
<TransitionGroup component="ul" className="inbox">
{items.map(item => (
<CSSTransition
key={item.id}
timeout={280}
classNames="row"
onExited={() => onArchive(item.id)}
>
<li className="inbox__row">
<span>{item.subject}</span>
<button onClick={() => onArchive(item.id)}>Archive</button>
</li>
</CSSTransition>
))}
</TransitionGroup>
);
}
The callback passed to onExited is the handoff point: the item stays in your state until the animation reports completion, which means your data model and the visual model never disagree. Note that the timeout value must match the CSS duration exactly. If the CSS runs for 400 ms and the component believes the exit took 280 ms, the node unmounts early, the animation snaps, and users perceive a flicker they cannot name.
Choreography with Framer Motion
Framer Motion pushes the same idea further by expressing animation declaratively, so the enter, exit and animate values live on one element and the library reconciles them. AnimatePresence watches its direct children: when a child's key disappears, it does not unmount it immediately, it plays the exit prop and unmounts on completion.
import { motion, AnimatePresence } from 'framer-motion';
export function TaskList({ tasks, onToggle }) {
return (
<AnimatePresence initial={false}>
{tasks.map(task => (
<motion.li
key={task.id}
layout
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0, transition: { duration: 0.22 } }}
transition={{ type: 'spring', stiffness: 380, damping: 34 }}
>
<label>
<input
type="checkbox"
checked={task.done}
onChange={() => onToggle(task.id)}
/>
{task.title}
</label>
</motion.li>
))}
</AnimatePresence>
);
}
The layout prop is the piece people underuse. When a checkbox is ticked and the item is filtered out of the visible list, every element below it shifts upward. Without layout animation those siblings jump; with it, the library measures the before and after positions and animates the delta, so remaining rows glide into place instead of teleporting.
Choosing between the three approaches
| Approach | Exit support | Bundle cost | Best for | Typical pitfall |
|---|---|---|---|---|
| CSS transitions and keyframes | No, element must stay mounted | Zero bytes | Hovers, toggles, skeletons, toasts | Timing constants scattered across stylesheets |
| React Transition Group | Yes, explicit leave callbacks | About 6 kB | Lists and routes where you already own the state | Timeout value drifting from the CSS duration |
| Framer Motion | Yes, declarative | About 30 kB gzipped | Modals, shared layout, gestures, staggered reveals | Animating everything, including trivial fades |
| View Transitions API | Browser-managed | Zero bytes | Multi-page navigation in Chromium | Incomplete support in Safari and Firefox |
Most production apps end up with all three: CSS for anything that never unmounts, a transition group for simple list leaves, and a motion library reserved for the two or three moments in the product that genuinely deserve choreography. Reaching for the heaviest tool on every fade is how a 40 kB page grows a 300 kB animation layer.
Keeping motion off the critical path
Animation runs at 60 frames per second, which gives you a hard 16 ms budget per frame, and roughly 6 ms of that is consumed by React's own render and commit work when a state update is involved. Anything that forces layout inside the loop, such as reading offsetHeight, animating width, or interpolating box-shadow, pushes the frame over budget and the animation stutters. Measure with the Performance panel while recording a scripted interaction: if the main thread shows long purple Layout or yellow Recalc Style bars inside the animation window, you are animating a property that forces layout.
Respect the user's motion preference as well. The prefers-reduced-motion media query is not a nice-to-have; for people with vestibular disorders, sliding and scaling content can cause real nausea. Wrap your most aggressive effects in it and offer an instant state change instead.
function usePrefersReducedMotion() {
const [reduced, setReduced] = useState(false);
useEffect(() => {
const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
setReduced(mq.matches);
const onChange = (e) => setReduced(e.matches);
mq.addEventListener('change', onChange);
return () => mq.removeEventListener('change', onChange);
}, []);
return reduced;
}
Debugging an animation that will not play
Work through the failure in order. Confirm the element is still in the DOM at the moment you expect the transition, because an early unmount is the most common cause. Then confirm a style value actually changes between frames, since a transition with identical start and end values never starts. After that check the property list: if opacity is in the transition and you only ever changed transform, nothing happens. Finally, verify that the class or prop is applied on the first frame after mount rather than in the same commit, because React will batch both changes and the browser will never see an intermediate value.
Common Mistakes
Animating layout properties such as height, top or margin inside a scrollable list
Fix: Animate transform and opacity instead, or collapse the height with a fixed transition and accept the single reflow.
Unmounting a component on the same tick that the exit transition begins
Fix: Hold the item in state until the exit callback fires, then remove it so the data model and the DOM agree.
Duplicating duration values in JavaScript and CSS
Fix: Define the duration once as a CSS custom property and read it in the component so the two can never drift apart.
Running heavy animations while React is re-rendering a large list
Fix: Isolate the animated subtree, memoize the rows, and let the transition run on the compositor while React commits.
Best Practices
- Pick the cheapest tool that supports the interaction: CSS first, a transition group second, a motion library only for choreography
- Wrap every non-essential effect in a prefers-reduced-motion check so users who need stillness get an instant state change
- Record a scripted interaction in the Performance panel before release and check that no Layout bar crosses the animation window
- Keep enter and exit durations asymmetric, with exits around twenty percent faster, so closing feels decisive rather than sluggish
- Test the animation with data sets of ten, one hundred and one thousand rows, because spring physics that feel right at ten items often crawl at a thousand
Key Takeaways
- CSS transitions handle everything that stays mounted, but cannot animate a node React has already removed
- Exit animation requires a library that keeps the element alive during a leave phase and unmounts only when the transition ends
- Only transform and opacity stay off the layout path, which is what keeps the frame inside its 16 millisecond budget
- The layout prop in Framer Motion turns positional jumps into smooth movement for sibling elements that shift after a removal
- Match JavaScript timeouts to CSS durations exactly, and honor prefers-reduced-motion before shipping any effect