Skip to content

Refresh ScrollTriggers on scrollHeight update #108

@leroykorterink

Description

@leroykorterink

We're currently refreshing ScrollTrigger when an animation is updated but this updates ScrollTrigger unnecessarily. We should definitely update ScrollTrigger when the scrollHeight of the document changes.

import ScrollTrigger from 'gsap/ScrollTrigger';
import { useRef } from 'react';
import { useAnimationLoop } from './useAnimationLoop';

/**
 * This hook is used to refresh the ScrollTrigger instance when the page height changes.
 * This is necessary to ensure that all scroll positions are correct.
 */
export function useScrollTrigger(): void {
  const previousScrollHeight = useRef(
    typeof document === 'undefined' ? 0 : document.scrollingElement?.scrollHeight,
  );

  useAnimationLoop(() => {
    const currentScrollHeight = document.scrollingElement?.scrollHeight ?? 0;

    if (currentScrollHeight !== previousScrollHeight.current) {
      ScrollTrigger.refresh();
    }

    previousScrollHeight.current = currentScrollHeight;
  }, true);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is neededreact

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions