Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refresh ScrollTriggers on scrollHeight update #108

Open
leroykorterink opened this issue Mar 16, 2023 · 2 comments
Open

Refresh ScrollTriggers on scrollHeight update #108

leroykorterink opened this issue Mar 16, 2023 · 2 comments
Labels
bug Something isn't working help wanted Extra attention is needed react

Comments

@leroykorterink
Copy link
Collaborator

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);
}
@leroykorterink leroykorterink added bug Something isn't working help wanted Extra attention is needed react labels Mar 16, 2023
@jesse-mm
Copy link
Collaborator

jesse-mm commented May 1, 2023

This function should be throttled as the ScrollTrigger.refresh() can be quite heavy. Also document.scrollingElement?.scrollHeight will trigger a layout every time raf gets called (if I'm not mistaken).

@VictorGa
Copy link
Contributor

@leroykorterink Are we creating a new hook? How this interacts with useScrollAnimation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed react
Projects
None yet
Development

No branches or pull requests

3 participants