Making GSAP ScrollTrigger wait for Next.js page transitions
ScrollTrigger measured too early on Viet Lasa Coffee. I made it wait for page transitions, then re-measure on filters and Sanity edits.

On Viet Lasa Coffee (Next.js 15 App Router, GSAP with ScrollTrigger, Lenis, content from Sanity), almost every heading splits into characters and slides up as you scroll to it. After a navigation or a content filter, an animation would sometimes fire before you'd scrolled anywhere near it. ScrollTrigger was measuring positions while the layout was still moving.
ScrollTrigger measures a layout that hasn't settled
ScrollTrigger works out start and end from the layout at the moment a trigger is created or refreshed. During a client-side route change the old page may still be unmounting while the new page's Server Components and fonts are still loading. A trigger created in that window plays early or in the wrong place.
Route changes, in-page filtering and Sanity edits all move the layout. They all go through a few global signals from @preact/signals-react. Every animated element reads those signals directly, along with the overlay and Lenis, which saves threading props or context through half the tree.
Cover the screen, then change the route
LinkEffect cancels the default click and puts the URL in a signal. A full-screen overlay fades in, and the layout calls router.push only after the fade is done:
// LinkEffect
onClick={(e) => {
routerEffect({ url: href, onClick }); // sets toggleState + urlState
e.preventDefault();
}}
// PageEffect/page: cover the screen first
const animationIn = contextSafe(() => {
resetLoader();
gsap.to(refContent.current, {
opacity: 1, pointerEvents: 'auto', duration: 0.8, ease: 'power3.out',
onComplete: setInComplete, // inCompleteState = true
});
});
// Layouts/Animation: navigate only once covered
useSignalEffect(() => {
if (!inCompleteState.value) return;
router.push(urlState.value, { scroll: true });
});
The reveal runs the other way. The overlay fades out once the new page has loaded, and its onComplete calls play() and schedules one more ScrollTrigger.refresh() a second later.
"Loaded" is a counter, because I didn't trust a fixed delay. Anything slow calls registerLoad() when it starts and unRegisterLoad() when it's done:
// useLogicAnimate
useEffect(() => {
resetLoader();
resetForPopup();
resetAnimation(); // isPlayState = false
let dbCheckLoaded = 0;
const clearTime = setInterval(() => {
if (loadState.peek() <= 0) dbCheckLoaded++;
else dbCheckLoaded = Math.max(dbCheckLoaded - 1, 0);
if (dbCheckLoaded > 3) {
loadedSate.value = true;
clearInterval(clearTime);
}
}, 50);
return () => clearInterval(clearTime);
}, [pathName]);
The gate opens when dbCheckLoaded exceeds three. Every 50 ms, a zero load count increments it and a nonzero count subtracts one rather than resetting it. This leaves room for late registrations, but doesn't require four consecutive zero-load ticks.
Right now it only waits on document.fonts.ready. (loadedSate is a typo in the real code, so I've left it.)
Triggers are created after the reveal
Every reusable effect (heading characters, line masks, fades, scale, parallax) goes through one hook, useAnimation. Each effect passes in an initAnimation that splits the text and hides it, plus a playAnimation with the tween:
// useAnimation (trimmed)
useSignalEffect(() => {
if (loadedSate.value) {
if (refTime.current) clearTimeout(refTime.current);
refTime.current = setTimeout(() => initAnimation(), 10);
}
});
const onHandleAnimation = contextSafe(() => {
const trl = ScrollTrigger.create({
trigger: trigger.current,
start: start || `top+=${calcTheshold}% 90%`,
once: true,
onEnter: () => setTimeout(() => playAnimation(), 50),
});
return () => trl.kill();
});
useSignalEffect(() => {
const clear = (isPlayTrigger.value && !isInPopup && onHandleAnimation()) || null;
return () => clear && clear();
});
When the gate opens, elements split and hide. Once the overlay has faded out, isPlayState turns true, and only then are triggers created against the new page's layout. The first visit has no overlay, so PageLoader calls play() 400 ms after the gate opens. The next navigation resets isPlayState, and the cleanup kills the old triggers.
isPlayState also pauses Lenis, which runs on GSAP's ticker (gsap.ticker.add(time => lenis.raf(time * 1000))). The same component subscribes ScrollTrigger.update() to Lenis's scroll event, but it does so on mount, before ReactLenis has created the instance. That listener never attaches. ScrollTrigger still updates from the window's own scroll events. Elements that don't need a whole trigger can use the isObserver option to get a plain IntersectionObserver instead.
Re-measuring without a navigation
Filtering journal cards or switching menu categories changes the page height, and the existing triggers keep their old measurements. useWindowResize puts a ResizeObserver on document.body and writes scrollHeight into a signal, and the layout refreshes ScrollTrigger when that value changes. My first debounce for it was broken from the start:
// first try: looks debounced, never re-runs
const debounceScroll = useComputed(() =>
debounce(() => scrollHeight.value, 300)
);
useSignalEffect(() => {
debounceScroll.value() && /* refresh each timeline */;
});
// the fix: debounce the signal itself
const debounceScroll = useDebouncedSignal(scrollHeight, 300);
useSignalEffect(() => {
debounceScroll.value &&
(gsap.globalTimeline.getChildren().forEach((t) => t.scrollTrigger?.refresh()),
gRefresh());
});
The first computed never reads scrollHeight.value. It only builds a debounced function, so it subscribes to no signal and the effect runs once. On top of that, a lodash debounce returns undefined until the wrapped function has been called at least once. What annoyed me is that it looks correct on a quick read.
useDebouncedSignal subscribes to the source signal and writes a second signal after 300 ms of quiet. The gRefresh() call (a global ScrollTrigger.refresh() on a timer) is needed because looping over gsap.globalTimeline only reaches triggers attached to a tween or timeline, while useAnimation creates standalone ones with ScrollTrigger.create.
When filtering, the tag button raises a global isPlayOutState flag and waits 500 ms for the old cards' outAnimation before changing the filter. The new cards then take the same useAnimation path as everything else, since loadedSate and isPlayState are already true.
Sanity edits reuse the body-height watcher
The Studio is embedded in the app with the Presentation tool, which toggles draft mode through two route handlers. The root layout reads await draftMode() (async since Next.js 15) before mounting the editing overlay. The first version imported VisualEditing from @sanity/visual-editing/next-pages-router by mistake; the right one comes from next-sanity, loaded client-only:
'use client';
import dynamic from 'next/dynamic';
// Dynamically import VisualEditing to avoid framer-motion client boundary issues
const VisualEditing = dynamic(
() => import('next-sanity').then((mod) => ({ default: mod.VisualEditing })),
{ ssr: false, loading: () => null }
);
In next-sanity 9.12, VisualEditing without live loaders falls back to revalidating the root layout. Server components re-render, but the client shell (layout, Lenis, signals) is still mounted on the same pathname and the load gate never resets. The body-height watcher picks up the change and re-measures the triggers after the edit is applied. I haven't tried newer next-sanity versions, so I can't promise the fallback still behaves this way.
Drafts, polling and three refresh calls
The preview can't read drafts yet, because pages fetch through a CDN client and <SanityLive /> isn't rendered anywhere, even though defineLive is ready in sanity/lib/live.ts. The load gate should await its promises instead of polling every 50 ms. SplitType splits once per page load, so a heading whose text changes in place needs a key based on its text.
ScrollTrigger.refresh() is also called from three places, including a useRefreshTrigger hook nobody uses. With one call site, the next time an animation fires early I'd at least know where to put the breakpoint.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.