useGSAP Hook: The Modern React Pattern
What you'll learn: How to use GSAP's official useGSAP hook to eliminate manual cleanup and scope animations properly in React 18+.
The Problem with Raw useEffect
You've been writing GSAP animations in useEffect, manually calling .kill() or .revert() in cleanup functions. This works, but it's error-prone—forget the cleanup, and you get memory leaks or stale animations. Plus, React 18's Strict Mode mounts components twice in development, making manual cleanup even trickier.
What useGSAP Does
The @gsap/react package provides a useGSAP hook that automatically handles cleanup and provides a gsap.context() scope. Think of it as a specialized useEffect that "speaks GSAP"—it knows when your component unmounts and automatically reverts all animations created inside it.
Basic pattern:
import { useGSAP } from '@gsap/react';
import { useRef } from 'react';
function Component() {
const container = useRef();
useGSAP(() => {
// All GSAP calls here are automatically scoped and cleaned up
gsap.to('.box', { x: 100 });
gsap.timeline()
.to('.circle', { rotation: 360 })
.to('.square', { scale: 2 });
}, { scope: container }); // scope limits queries to this ref
return <div ref={container}>...</div>;
}
The scope option acts like a container—GSAP selectors only target elements inside that ref. No more accidental cross-component interference.
Why This Matters
With useGSAP, you never write cleanup code manually. The hook handles React 18's double-mounting gracefully. It's the official GSAP team's answer to React's lifecycle quirks, making your animations both safer and cleaner.
Key Takeaway: useGSAP from @gsap/react replaces manual useEffect patterns with automatic cleanup and context scoping, making GSAP animations React 18-compatible by default.