New: remix a demo site in your browser – no sign-up, nothing to install. Try it

← Blog

GSAP Scroll Animation in React: Setup and StrictMode Fixes

· 9 min read

Key takeaways

  • Register ScrollTrigger once at module level, then create tweens inside useLayoutEffect and kill them on cleanup.
  • Wrap animation setup in gsap.context() and return ctx.revert() from useEffect so React 18 StrictMode's double mount never leaves duplicate triggers.
  • Pinned scenes use a gsap.timeline() with pin: true and scrub: 1, and pinSpacing keeps following content from sliding under the pinned section.
  • In Next.js, mark components 'use client' and dynamic-import GSAP with ssr: false so ScrollTrigger never touches the server.
  • Call ScrollTrigger.refresh() after images, fonts or state changes alter page height, since ScrollTrigger caches measurements.

A gsap scroll animation in React works differently than in a plain HTML page: ScrollTrigger registrations collide with StrictMode's double-mount, cleanup runs twice, and Next.js SSR tries to run animation code on the server. This guide covers setup, gsap.context() cleanup, pinned scenes, text reveals and parallax with copy-paste examples, then compares hand-coded GSAP against WordPress-native options for client work.

How do you register ScrollTrigger in a React component?

Install GSAP, register the plugin once at module level, then create your tweens inside useLayoutEffect and kill them on cleanup.

Install and register once

Run npm install gsap, then put this at the top of the file, outside any component:

import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);

GSAP's ScrollTrigger docs cover registration and the global options you can tweak later.

First tween: fade an image in on scroll

The first tween worth shipping is a fade-up on an image as it enters the viewport. Give the element a ref, then create the tween against that ref rather than a class selector, so React re-renders never orphan your animation. A minimal version is gsap.fromTo(img, { autoAlpha: 0, y: 40 }, { autoAlpha: 1, y: 0, scrollTrigger: { trigger: img, start: "top 80%", toggleActions: "play none none none" } }). Return a cleanup function that calls tween.kill() so triggers stay clean across mounts. Reach for useLayoutEffect instead of useEffect so styles apply before the browser paints, which prevents the image flashing visible for one frame before the tween hides it. If you ship client sites in WordPress instead of React, the same pattern is covered in our sticky scroll guide.

Why does your GSAP scroll animation break in React StrictMode?

React 18's StrictMode mounts, unmounts, and remounts every component in development. Your scroll animation code runs twice, and the first run's tweens and ScrollTriggers survive into the second run. Two triggers now watch the same element, so you get doubled tweens, jittery scrubbing, or triggers that fire with the wrong start position.

What the double mount does to ScrollTrigger

Each mount calls gsap.to() and ScrollTrigger.create() again. Without cleanup, the first set of triggers keeps listening to scroll events while the second set animates the same properties. The result: animations that jump, replay out of order, or freeze partway through a pinned scene. This only happens in development, but it makes the dev environment useless for testing scroll work.

Fix: create animations inside gsap.context()

Wrap your animation setup in gsap.context() and return the cleanup function from useEffect. On the second mount, the context from the first run has already been reverted, so you start clean:

useEffect(() => {
  const ctx = gsap.context(() => {
    gsap.to(".card", {
      scrollTrigger: { trigger: ".section", scrub: true },
      y: -100,
    });
  });
  return () => ctx.revert();
}, []);

ctx.revert() kills every tween and trigger created inside that context in one call. The same pattern underpins the pinned scenes and text reveals in the rest of this guide, and the scroll animation in WordPress: 5 guides with live demos show it applied outside React, so it's worth getting right once.

How do you clean up ScrollTrigger instances on unmount?

Every ScrollTrigger you create attaches scroll listeners to the window. If the component unmounts without killing them, the listeners survive, fire on elements that no longer exist, and throw errors on route changes.

The cleanup return, line by line

Return a function from useEffect and run three steps: call ctx.revert() on your gsap.context() to undo inline styles and animations, call ScrollTrigger.getAll().forEach(t => t.kill()) for any triggers created outside the context, then ScrollTrigger.refresh() so remaining triggers recalculate against the new page height. React's docs on useEffect cleanup cover why the return function runs both on unmount and before every re-run of the effect.

Symptoms of missing cleanup

Dead triggers show up as console errors referencing removed nodes, scroll position jumping after navigation, and animations replaying on elements from a previous page. If you see those, a useEffect is missing its return.

The same discipline applies to no-code tools: a scroll builder should tear down its own listeners between pages, which is the baseline we hold Midground to.

How do you build a pinned scroll scene in React with GSAP?

A pinned scene holds a section in the viewport while a timeline plays inside it. The pattern: one gsap.timeline() with scrollTrigger: { trigger, start: "top top", end: "+=1500", pin: true, scrub: 1 }, then steps added with tl.to() in sequence.

Pinned scene code

useLayoutEffect(() => {
  const tl = gsap.timeline({
    scrollTrigger: {
      trigger: sceneRef.current,
      start: "top top",
      end: "+=1500",
      pin: true,
      scrub: 1,
    },
  });
  tl.from(".card", { opacity: 0, y: 40, stagger: 0.3 })
    .to(".headline", { scale: 1.2 })
    .to(".panel", { xPercent: -100 });
  return () => { tl.scrollTrigger?.kill(); tl.kill(); };
}, []);

pinSpacing and layout shift

pinSpacing: true (the default) adds padding equal to the pin duration so following content doesn't slide under the pinned section. Set it to false and that space vanishes, causing layout shift. If your theme's CSS adds margins to sections, the spacer can misalign; test on a clean template. If you'd rather skip this wiring entirely, Midground's feature set builds pinned scenes visually on WordPress, though you lose the frame-level control scrub timelines give you here.

How do you animate text on scroll in React with GSAP?

Word-by-word reveal with a scrub timeline

Split the headline yourself, no paid plugin needed. Wrap each word in a span, then animate them with a stagger:

useEffect(() => {
  const words = ref.current.querySelectorAll("span");
  const tl = gsap.timeline({
    scrollTrigger: { trigger: ref.current, start: "top 80%", end: "top 30%", scrub: true },
  });
  tl.from(words, { yPercent: 110, opacity: 0, stagger: 0.08 });
  return () => { tl.scrollTrigger?.kill(); tl.kill(); };
}, []);

The scrub value ties progress to scroll position, so the reveal tracks the user's finger. Set overflow: hidden on the headline wrapper for the masked-line effect.

When to reach for SplitText

GSAP's SplitText plugin handles line-splitting on responsive layouts, where manual word spans fall short on resize. It became free with GSAP 3.13, so try it before writing your own splitter. If you're shipping this pattern on client WordPress sites rather than React, Midground bakes word and line reveals into its visual builder, with tiering for freelancers on the pricing page.

How does GSAP ScrollTrigger differ from CSS scroll snap animations?

Scroll snap is CSS deciding where the viewport stops; ScrollTrigger is JavaScript scrubbing a timeline as the user scrolls. Snap gives you fixed rest points for free. ScrollTrigger gives you scrubbed timelines, pinned scenes and progress-based control, at the cost of running JavaScript on the client, which is why server-rendered React components need the SSR guards covered later in this guide.

Comparison table

CSS scroll snapScroll-driven CSSGSAP ScrollTrigger
What it controlsSnap points onlyScroll-linked effectsTimelines, pins, scrubbing
Needs JavaScriptNoNoYes
Control levelLowMediumHigh
Works in a builder themeYesPartiallyNeeds integration

When CSS alone is enough

If the effect is "sections stop at full height," scroll-snap-type on the container does it with no library. Pair it with scroll-driven CSS animations for fades and parallax where browser support allows. Reach for ScrollTrigger when you need a scene to hold while several elements animate in sequence, or when the animation must reverse cleanly as the user scrolls back up.

What breaks a gsap scroll animation in Next.js and SSR?

ScrollTrigger reads window dimensions when it registers, so importing it at the top level of a server-rendered component crashes the build. Keep GSAP out of the server path entirely.

use client and dynamic import

Mark the component with 'use client', then load GSAP with next/dynamic and ssr: false so the module only evaluates in the browser:

const ScrollScene = dynamic(() => import('./ScrollScene'), { ssr: false });

Inside ScrollScene, register plugins inside useEffect, never at module scope. That guarantees window and document exist.

Hydration mismatch symptoms

If ScrollTrigger runs before hydration, you get hydration warnings, a flash of unanimated content, or measurements taken against a half-painted layout, which offsets every trigger. Run gsap.context() inside useEffect, then call ScrollTrigger.refresh() in a useEffect after images and fonts load. The refresh recalculates pin distances against the final layout.

Where can you find working GSAP scroll animation examples for React?

Official and community demos

GreenSock's own docs ship runnable demos for ScrollTrigger, and the CodePen community holds thousands of pinned scenes, text reveals and parallax effects you can fork free. Search "ScrollTrigger" on CodePen and sort by popularity; most pens are vanilla JS, which is fine, because the animation logic ports directly.

Porting a CodePen into React

Take the pen's timeline and put it inside useLayoutEffect, then call ScrollTrigger.create() or register triggers there. Replace document.querySelector targets with useRef, and return a cleanup function that kills the triggers. Anything CSS-driven in the pen, like scroll snap, check against browser support for CSS scroll-driven and scroll snap features before relying on it in client work.

Should you hand-code GSAP in React, or use a WordPress-native scroll builder?

Criteria applied honestly

Judge every option on four things: page speed, design control, cleanup between projects, and cost. Hand-coded GSAP wins on control and speed, but you write the pin logic, the cleanup, and the SSR guards yourself, per site. Page builders like Elementor and Bricks trade that control for faster delivery. Block-level tools such as Greenshift and GenerateBlocks sit between them.

Midground targets the same trade: pinned scenes and parallax without writing the timeline code, on a theme built to keep pages fast. Where it falls short: React and Next.js sites are outside it entirely, and everything above is hand-written GSAP. If your client work is React, this article's patterns are the workflow.

When hand-coding still wins

If a client needs a scroll sequence no builder ships, or you already have the ScrollTrigger patterns from this guide, code it. Otherwise, for five-site freelancers, a WordPress-native builder is the faster path to a shipped page.

FAQ

Do I need useLayoutEffect instead of useEffect for GSAP ScrollTrigger in React?

Not always, but it's the safer default for entrance animations. useLayoutEffect applies styles before the browser paints, so elements start hidden instead of flashing visible for one frame. Use plain useEffect when you need the DOM only after paint, such as registering plugins or calling ScrollTrigger.refresh().

How do I refresh ScrollTrigger after React state or images change the page height?

ScrollTrigger caches measurements, so any layout change shifts your trigger positions. Call ScrollTrigger.refresh() after the change settles: inside a useEffect that depends on the relevant state, or on image load events. Refresh recalculates start and end positions and pin distances against the new page height.

Is GSAP ScrollTrigger free to use in commercial client projects?

Yes. Since GSAP 3.13, every plugin, including ScrollTrigger and SplitText, ships under a license that permits commercial use at no cost. You can use it on client sites, SaaS products, and paid work without paying GreenSock. Only optional paid offerings, like premium support or club extras, cost money.

Can I use GSAP scroll animations inside Elementor or a WordPress theme without React?

Yes. Register ScrollTrigger in a plain script enqueued by your theme or added via a code snippet, then target elements by selector. The React-specific problems, StrictMode double mounts and SSR guards, disappear. Alternatively, WordPress-native builders like Midground or Greenshift build pinned scenes and parallax without writing timeline code.

Why does my ScrollTrigger animation jump or stutter on mobile?

Mobile browsers resize the viewport as the address bar collapses, which invalidates ScrollTrigger's measurements mid-scroll. Set refreshPriority and ignoreMobileResize, and refresh after fonts and images load. For pinned scenes, prefer scrub values of 1 or higher to smooth tracking, and test whether the stutter comes from layout shift rather than the tween itself.