Course contentsShow
← React
Lesson 2001 of 2,39645. AnimationsFree lesson

Installing GSAP and Basic Setup in React

Adding GSAP to a React project and understanding the @gsap/react package for better integration.

Installing GSAP and Basic Setup in React

What you'll learn: How to add GSAP to your React project and leverage the official @gsap/react package for seamless integration.

Why GSAP Needs Special Setup in React

GSAP is a powerful imperative animation library, but React's declarative paradigm creates friction. You manipulate DOM elements directly with GSAP, while React expects to own the DOM. The @gsap/react package bridges this gap with React-friendly hooks and utilities.

Installing the Packages

You need two packages: the core GSAP library and the official React wrapper:

npm install gsap @gsap/react

The @gsap/react package provides:

  • useGSAP hook: A React-safe wrapper for GSAP code with automatic cleanup
  • Context-aware animations: Scopes animations to components properly
  • Better performance: Minimizes unnecessary re-renders

Basic Setup Pattern

While you could use GSAP directly in useEffect, the useGSAP hook prevents common pitfalls like memory leaks and timing issues:

import { useGSAP } from '@gsap/react';
import gsap from 'gsap';

function AnimatedBox() {
  const boxRef = useRef(null);

  useGSAP(() => {
    // GSAP code runs once on mount
    gsap.to(boxRef.current, {
      x: 200,
      duration: 1
    });
  });

  return <div ref={boxRef}>I'll slide right!</div>;
}

Think of useGSAP as a specialized useEffect designed specifically for GSAP animations—it handles cleanup and ensures animations don't conflict with React's rendering lifecycle.

Key Takeaway: Install gsap and @gsap/react together; use the useGSAP hook instead of raw useEffect to let GSAP manipulate refs safely within React's component lifecycle.