CSS Transitions for Simple State Changes
What you'll learn: How to smoothly animate basic state changes in React using plain CSS transitions instead of heavyweight animation libraries.
The Core Idea
After exploring powerful animation libraries like GSAP, Framer Motion, and React Spring, it's crucial to recognize when you don't need them. CSS transitions handle the vast majority of everyday UI animations — hover effects, button states, toggles, modals fading in — without any JavaScript orchestration beyond changing a class or style.
The pattern is simple: React updates state, which changes a className or inline style, and CSS handles the visual transition smoothly. No libraries, no bundle weight, just the transition property doing its job.
When CSS Transitions Shine
Use CSS transitions when:
- The animation triggers from a state change (open/closed, active/inactive)
- You're animating CSS properties like
opacity,transform,background-color - You don't need complex sequencing or choreography
Think of CSS transitions like automatic transmission in a car — you change gears (states), and the engine (browser) smoothly handles the shift. Animation libraries are manual transmission: more control, but unnecessary for most driving.
The Pattern in React
function TogglePanel() {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button onClick={() => setIsOpen(!isOpen)}>
Toggle
</button>
<div className={isOpen ? 'panel open' : 'panel'}>
Content here
</div>
</div>
);
}
.panel {
max-height: 0;
opacity: 0;
overflow: hidden;
transition: max-height 0.3s ease, opacity 0.3s ease;
}
.panel.open {
max-height: 500px;
opacity: 1;
}
React changes the class; CSS animates the properties. Clean separation of concerns.
Key Takeaway: For simple state-driven animations (toggles, hovers, focus states), CSS transitions require zero JavaScript animation code and perform beautifully — always reach for them before importing an animation library.