useSpring: Animating a Single Element
You'll learn: How to use React Spring's useSpring hook to create smooth, physics-based animations for a single element by controlling CSS properties.
What is useSpring?
useSpring is React Spring's foundational hook for animating a single set of values. Unlike duration-based animations, it uses spring physics to create natural-feeling motion. You pass it an object describing your target state (like opacity, position, or scale), and it returns animated values you can apply to your elements.
Think of it like stretching a rubber band — instead of moving at a constant speed for a fixed duration, the animation accelerates and decelerates naturally based on tension and friction.
Basic Usage
import { useSpring, animated } from '@react-spring/web';
function FadeInBox() {
const springs = useSpring({
from: { opacity: 0 },
to: { opacity: 1 }
});
return <animated.div style={springs}>I fade in!</animated.div>;
}
The useSpring hook returns an object of animated values. You must use animated.div (or any animated.* component) instead of a regular HTML element — this special wrapper knows how to handle spring-animated values.
Controlling Multiple Properties
const springs = useSpring({
from: { opacity: 0, transform: 'translateY(-20px)' },
to: { opacity: 1, transform: 'translateY(0px)' }
});
You can animate opacity, transforms, colors, and most CSS properties simultaneously. Each property follows the same spring physics, creating cohesive motion.
State-Driven Animations
const [isVisible, setIsVisible] = useState(false);
const springs = useSpring({
opacity: isVisible ? 1 : 0,
transform: isVisible ? 'scale(1)' : 'scale(0.8)'
});
When state changes, useSpring automatically animates from the current values to the new targets.
Key Takeaway: useSpring creates physics-based animations for a single element by accepting target CSS properties and returning animated values you apply via the animated.* component wrapper.