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

ScrollTrigger Plugin in React Components

Integrating GSAP's ScrollTrigger for scroll-driven animations, handling registration and cleanup properly.

ScrollTrigger Plugin in React Components

You'll learn: How to integrate GSAP's ScrollTrigger plugin to create animations that respond to scroll position, while managing React's lifecycle properly.

Why ScrollTrigger in React

ScrollTrigger is GSAP's powerful plugin for triggering animations based on scroll position. It lets you animate elements as they enter/exit the viewport, pin sections while scrolling, or scrub through animations tied directly to scroll progress. In React, you need careful setup to avoid memory leaks and stale references.

Registering the Plugin

Before using ScrollTrigger, you must register it once with GSAP:

import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

// Register once, typically at the top of your component file
gsap.registerPlugin(ScrollTrigger);

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

  useEffect(() => {
    gsap.to(boxRef.current, {
      x: 500,
      scrollTrigger: {
        trigger: boxRef.current,
        start: "top center", // when top of element hits center of viewport
        end: "bottom top",
        scrub: true // tie animation progress to scroll position
      }
    });
  }, []);

  return <div ref={boxRef} className="box">Scroll to animate me</div>;
}

Critical Cleanup Pattern

ScrollTrigger instances must be explicitly killed in React's cleanup function to prevent duplicate triggers on re-renders:

useEffect(() => {
  const trigger = ScrollTrigger.create({
    trigger: boxRef.current,
    onEnter: () => gsap.to(boxRef.current, { opacity: 1 })
  });

  return () => {
    trigger.kill(); // Essential cleanup
  };
}, []);

Key Takeaway: ScrollTrigger brings scroll-driven animations to React components—always register the plugin with gsap.registerPlugin(ScrollTrigger) and call trigger.kill() in your cleanup function to prevent memory leaks and duplicate animations.