Imperative Updates with set()
You'll learn how to trigger spring animations on-demand in response to events, rather than relying solely on reactive state changes.
The Declarative vs Imperative Choice
So far, you've used useSpring declaratively—the animation runs automatically when state changes. But sometimes you need more control: triggering an animation in response to a click, hover, or fetch completion without tying it to component state. That's where the set() function comes in.
When you call useSpring, it returns a tuple: [springValues, api]. The second element, api, contains methods including set() that let you update the animation target imperatively:
const [springs, api] = useSpring(() => ({
from: { x: 0 },
}));
function handleClick() {
// Trigger animation without changing React state
api.set({ x: 100 });
}
Think of set() like a remote control for your animation—you press a button (call the function) and the spring responds immediately.
When to Use Imperative Updates
Use set() when:
- Animations are event-driven (button clicks, gestures)
- You don't want to clutter component state with animation values
- Coordinating multiple animation sequences
- Performance matters (avoiding unnecessary re-renders)
const [springs, api] = useSpring(() => ({
opacity: 1,
config: { tension: 170, friction: 26 },
}));
function fadeOut() {
api.set({ opacity: 0 });
}
function fadeIn() {
api.set({ opacity: 1 });
}
The spring configuration (tension, friction, mass) you defined initially still applies—set() just changes the target destination.
Key Takeaway: The set() function from useSpring's API lets you trigger animations imperatively in event handlers, keeping animation logic separate from React state while preserving spring physics.