useGSAP() Hook (GSAP with React the Right Way)

  • useGSAP() is the official GSAP React hook that simplifies animations, scoping, and cleanup in React apps.
  • Introduction

    When using GSAP in React, managing animations with useEffect() can become messy and error-prone.

    To solve this, GreenSock GSAP introduced useGSAP(), an official React hook that:

    • Automatically scopes animations

    • Cleans up on component unmount

    • Prevents memory leaks

    • Makes GSAP + React work smoothly together

    👉 useGSAP() is the recommended way to use GSAP in React.

useGSAP(() => {
  gsap.to(".box", { x: 200 });
});

Installation / Setup

npm install gsap

Import useGSAP

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

gsap.registerPlugin(useGSAP);

useGSAP(() => {
  gsap.to(".box", { x: 300 });
});

Scoped Animations (Very Important)

const container = useRef();

useGSAP(() => {
  gsap.to(".box", { y: 100 });
}, { scope: container });

<div ref={container}>
  <div className="box"></div>
</div>
  • Parameters / Options

    OptionMeaningExample
    scopeLimits selectors{ scope: ref }
    dependenciesRe-run animation{ dependencies:[state] }
    revertOnUpdateReset on changetrue

Simple React Animation

useGSAP(() => {
  gsap.from(".card", {
    opacity: 0,
    y: 50,
    duration: 0.6
  });
});

Timeline with useGSAP

useGSAP(() => {
  const tl = gsap.timeline();
  tl.from(".title", { y: 50, opacity: 0 })
    .from(".btn", { scale: 0 });
});

Animation on State Change

useGSAP(() => {
  gsap.to(".box", { x: active ? 300 : 0 });
}, { dependencies: [active] });

useGSAP + ScrollTrigger

useGSAP(() => {
  gsap.from(".section", {
    scrollTrigger: {
      trigger: ".section",
      start: "top 80%"
    },
    y: 100,
    opacity: 0
  });
});
  • Best Practices

    • Always use scope

    • Prefer class selectors inside scope

    • Use timelines for complex UI

    • Combine with ScrollTrigger safely

  • Comparison

    MethodReact SafeCleanup
    useEffect + GSAP❌ NoManual
    useLayoutEffect⚠️ RiskyManual
    useGSAP()✅ YesAutomatic
  • Quick Summary

    • useGSAP() is the official GSAP React hook

    • Automatically handles cleanup

    • Prevents animation bugs

    • Scoped & performant

    • Best practice for React + GSAP