by @bbeierle12
GSAP integration with React including useGSAP hook, ref handling, cleanup patterns, and context management. Use when implementing GSAP animations in React components, handling component lifecycle, or building reusable animation hooks.
React-specific patterns for GSAP animations.
npm install gsap @gsap/react
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
function Component() {
const containerRef = useRef(null);
useGSAP(() => {
gsap.to('.box', { x: 200, duration: 1 });
}, { scope: containerRef });
return (
<div ref={containerRef}>
<div className="box">Animated</div>
</div>
);
}
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
function AnimatedComponent() {
const container = useRef(null);
useGSAP(() => {
// All GSAP animations here
gsap.from('.item', {
opacity: 0,
y: 50,
stagger: 0.1
});
}, { scope: container }); // Scope limits selector queries
return (
<div ref={container}>
<div className="item">Item 1</div>
<div className="item">Item 2</div>
<div className="item">Item 3</div>
</div>
);
}
function AnimatedComponent({ isOpen }) {
const container = useRef(null);
useGSAP(() => {
gsap.to('.drawer', {
height: isOpen ? 'auto' : 0,
duration: 0.3
});
}, { scope: container, dependencies: [isOpen] });
return (
<div ref={container}>
<div className="drawer">Content</div>
</div>
);
}
function Component() {
const container = useRef(null);
const { context, contextSafe } = useGSAP(() => {
gsap.to('.box', { x: 200 });
}, { scope: container });
// Use contextSafe for event handlers
const handleClick = contextSafe(() => {
gsap.to('.box', { rotation: 360 });
});
return (
<div ref={container}>
<div className="box" onClick={handleClick}>Click me</div>
</div>
);
}
function SingleElement() {
const boxRef = useRef(null);
useGSAP(() => {
gsap.to(boxRef.current, {
x:...