Files

7.5 KiB

GSAP & ScrollTrigger Engineering Recipes

Engine: GSAP 3.x with ScrollTrigger & @gsap/react (useGSAP hook). Target Framework: React 18/19 & Next.js 14/15 (App Router). Language: TypeScript.


⚡ 1. The Gold Standard React Lifecycle (useGSAP)

Never run raw gsap.to() in a basic useEffect without cleanup. In React 18+ (especially with StrictMode double-mounting), uncleaned ScrollTrigger instances leak memory and cause visual duplication.

npm install gsap @gsap/react

Safe Component Scaffolding:

'use client';

import React, { useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';

// Register plugins once outside render
if (typeof window !== 'undefined') {
  gsap.registerPlugin(ScrollTrigger, useGSAP);
}

export const CreativeScene: React.FC = () => {
  const containerRef = useRef<HTMLDivElement>(null);

  useGSAP(
    () => {
      // All selectors inside this hook are automatically scoped to containerRef!
      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: containerRef.current,
          start: 'top top',
          end: '+=200%',
          pin: true,
          scrub: 1, // 1-second organic smoothing
          anticipatePin: 1,
          invalidateOnRefresh: true, // Recalculate on screen resize
        },
      });

      tl.from('.narrative-headline', {
        yPercent: 100,
        opacity: 0,
        ease: 'power3.out',
      })
      .to('.hero-image', {
        scale: 1.2,
        clipPath: 'polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)',
        ease: 'power2.inOut',
      }, '<') // Run concurrently with headline
      .to('.narrative-headline', {
        yPercent: -100,
        opacity: 0,
        ease: 'power2.in',
      }, '+=0.5');
    },
    { scope: containerRef } // Crucial: automatic cleanup on unmount!
  );

  return (
    <section ref={containerRef} className="relative h-screen w-full overflow-hidden bg-neutral-950 text-white">
      <div className="hero-image absolute inset-0 z-0 scale-100 bg-cover bg-center" style={{ backgroundImage: "url('/hero.jpg')", clipPath: 'polygon(15% 15%, 85% 15%, 85% 85%, 15% 85%)' }} />
      <div className="relative z-10 flex h-full items-center justify-center">
        <h1 className="narrative-headline text-7xl font-bold tracking-tighter">ENGINEERED ELEGANCE</h1>
      </div>
    </section>
  );
};

🚂 2. Horizontal Storytelling Track (Pinned Viewport)

A horizontal gallery that converts vertical page scroll into smooth sideways translation:

'use client';

import React, { useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';

export const HorizontalNarrative: React.FC = () => {
  const targetRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);

  useGSAP(
    () => {
      const track = trackRef.current;
      if (!track) return;

      // Calculate total horizontal scroll distance
      const getScrollAmount = () => -(track.scrollWidth - window.innerWidth);

      gsap.to(track, {
        x: getScrollAmount,
        ease: 'none', // Strict linear scrubbing tied to scrollbar
        scrollTrigger: {
          trigger: targetRef.current,
          start: 'top top',
          end: () => `+=${track.scrollWidth - window.innerWidth}`,
          pin: true,
          scrub: 0.8,
          invalidateOnRefresh: true,
        },
      });
    },
    { scope: targetRef }
  );

  return (
    <div ref={targetRef} className="relative h-screen w-full overflow-hidden bg-neutral-900">
      <div ref={trackRef} className="flex h-full w-fit items-center gap-12 px-16">
        {[1, 2, 3, 4, 5].map((index) => (
          <div
            key={index}
            className="flex h-[70vh] w-[60vw] md:w-[40vw] flex-shrink-0 flex-col justify-end rounded-2xl bg-neutral-800 p-8 text-white border border-neutral-700/50"
          >
            <span className="text-sm font-mono text-neutral-400">PHASE 0{index}</span>
            <h2 className="text-4xl font-semibold mt-2">Cinematic Dimension {index}</h2>
          </div>
        ))}
      </div>
    </div>
  );
};

✂️ 3. Editorial clip-path Curtain Reveal

A cinematic transition where an image or video expands from a small geometric window into full bleed as the user scrolls into it:

'use client';

import React, { useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';

export const CurtainExpand: React.FC = () => {
  const containerRef = useRef<HTMLDivElement>(null);

  useGSAP(
    () => {
      gsap.fromTo(
        '.curtain-media',
        {
          clipPath: 'inset(25% 30% 25% 30% round 32px)',
          scale: 1.15,
        },
        {
          clipPath: 'inset(0% 0% 0% 0% round 0px)',
          scale: 1.0,
          ease: 'power2.inOut',
          scrollTrigger: {
            trigger: containerRef.current,
            start: 'top bottom',
            end: 'center center',
            scrub: 1.2,
          },
        }
      );
    },
    { scope: containerRef }
  );

  return (
    <section ref={containerRef} className="relative min-h-[140vh] w-full bg-black py-24">
      <div className="curtain-media sticky top-0 h-screen w-full overflow-hidden will-change-[clip-path]">
        <img
          src="/cinematic-backdrop.jpg"
          alt="Curtain reveal"
          className="h-full w-full object-cover"
        />
      </div>
    </section>
  );
};

🔤 4. Staggered Kinetic Typography (Characters & Words)

Splitting text and revealing each glyph with a subtle rotation and opacity wave:

'use client';

import React, { useRef } from 'react';
import gsap from 'gsap';
import { useGSAP } from '@gsap/react';

export const KineticTitle: React.FC<{ text: string }> = ({ text }) => {
  const textRef = useRef<HTMLHeadingElement>(null);

  useGSAP(
    () => {
      const letters = textRef.current?.querySelectorAll('.char');
      if (!letters || letters.length === 0) return;

      gsap.from(letters, {
        yPercent: 120,
        rotateX: -45,
        opacity: 0,
        stagger: 0.02,
        duration: 0.9,
        ease: 'power3.out',
        scrollTrigger: {
          trigger: textRef.current,
          start: 'top 85%',
        },
      });
    },
    { scope: textRef }
  );

  return (
    <h2
      ref={textRef}
      className="overflow-hidden text-6xl md:text-8xl font-black uppercase tracking-tight [perspective:1000px]"
    >
      {text.split('').map((char, i) => (
        <span
          key={i}
          className="char inline-block will-change-transform will-change-opacity"
        >
          {char === ' ' ? '\u00A0' : char}
        </span>
      ))}
    </h2>
  );
};

🏎️ 5. Smooth Scroll Synergy (Lenis + ScrollTrigger)

When using modern smooth scroll libraries like Lenis, you must synchronize Lenis's ticker with GSAP's ticker:

import Lenis from 'lenis';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

export function setupSmoothScroll() {
  const lenis = new Lenis({
    duration: 1.2,
    easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
    smoothWheel: true,
  });

  // Synchronize Lenis scroll with ScrollTrigger
  lenis.on('scroll', ScrollTrigger.update);

  gsap.ticker.add((time) => {
    lenis.raf(time * 1000);
  });

  gsap.ticker.lagSmoothing(0);

  return lenis;
}