Controlling Playback: play(), pause(), reverse()
What you'll learn: How to store GSAP timeline references and expose playback controls to give users or your application full control over animation playback.
The Core Idea
Unlike declarative React animation libraries, GSAP timelines are imperative objects you can control like a video player. Once you create a timeline, you can start, stop, reverse, or scrub through it at will. The key is storing the timeline reference in a useRef so it persists across renders, then exposing control methods through event handlers or component state.
Why This Matters
This approach lets you build interactive animations — buttons that pause/resume effects, scroll-triggered sequences that reverse on scroll-up, or UI elements that "rewind" when conditions change. You're treating animations as controllable processes, not fire-and-forget effects.
The Pattern
import { useRef, useEffect } from 'react';
import gsap from 'gsap';
function PlaybackControls() {
const boxRef = useRef(null);
const timelineRef = useRef(null); // Store timeline here
useEffect(() => {
timelineRef.current = gsap.timeline({ paused: true })
.to(boxRef.current, { x: 300, duration: 2 })
.to(boxRef.current, { rotation: 360, duration: 1 });
}, []);
return (
<div>
<div ref={boxRef} style={{ width: 100, height: 100, background: 'blue' }} />
<button onClick={() => timelineRef.current?.play()}>Play</button>
<button onClick={() => timelineRef.current?.pause()}>Pause</button>
<button onClick={() => timelineRef.current?.reverse()}>Reverse</button>
</div>
);
}
Notice { paused: true } — the timeline exists but doesn't auto-play. We then call .play(), .pause(), or .reverse() directly on the stored timeline object.
Key Takeaway: Store GSAP timelines in useRef to preserve them across renders, then expose playback methods (play(), pause(), reverse()) through event handlers for full imperative control over your animations.