Vinod

November 13, 2024

Customize Lenis scroll configuration, depending upon each section.

1. Create Custom hooks

eg: path: app/logic/useCustomLenisScroll.js

import React, { useRef, useEffect, useState } from "react";
import { useLenis } from "lenis/react";

const useCustomLenisScroll = (customDuration = 1) => {
  const container = useRef(null); // Remove TypeScript type annotations
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsVisible(entry.isIntersecting);
    });

    if (container.current) {
      observer.observe(container.current);
    }

    return () => {
      if (container.current) {
        observer.unobserve(container.current);
      }
    };
  }, []);

  const lenis = useLenis();
  const initialDuration = 1;

  useEffect(() => {
    const handleScroll = () => {
      isVisible ? lenis.options.duration = customDuration : lenis.options.duration = initialDuration
    };

    lenis.on("scroll", handleScroll);

    return () => {
      lenis.off("scroll", handleScroll);
    };
  }, [isVisible, lenis, customDuration, initialDuration]);

  return {
    container,
    isVisible,
  };
};

export default useCustomLenisScroll;

2. Import this Hooks to your Components

import React from "react";
import useCustomLenisScroll from "./useCustomLenisScroll";

const MyComponent = () => {
  const { container, isVisible } = useCustomLenisScroll(5); // Custom duration set to 5

  return (
    <div>
      <div style="{{">Scroll Down</div>
      <div style="{{">
        {isVisible ? "I am visible!" : "I am not visible!"}
      </div>
      <div style="{{">More content below</div>
    </div>
  );
};

export default MyComponent;

In this example, the useCustomLenisScroll custom hook takes a custom value as a parameter and updates the Lenis scroll duration when the section becomes visible in the viewport.

Top comments
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments