Skip to content
Advertisement

How to correctly use Locomotive Scroll with Next.js routing?

I’m using locomotive-scroll with Next.js and all working fine. But after route to a different page, my scroll won’t destroy and 2 scrolls overlap each other.

How to correctly reinit locomotive-scroll in Next.js after route?

My code example:

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        import("locomotive-scroll").then((locomotiveModule) => {
            let scroll = new locomotiveModule.default({
                el: document.querySelector("[data-scroll-container]"),
                smooth: true,
                smoothMobile: false,
                resetNativeScroll: true,
             });
          
             scroll.destroy();  //<-- DOESN'T WORK OR IDK
    
             setTimeout(function () {
                 scroll.init();
             }, 400);
         });
     });
    
     return (
         <main data-scroll-container>
             <Component {...pageProps} />
         </main>
     );
}

Advertisement

Answer

You should move the scroll.destroy call to the cleanup phase of the useEffect. You also don’t need to explicitly call scroll.init().

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        let scroll;
        import("locomotive-scroll").then((locomotiveModule) => {
            scroll = new locomotiveModule.default({
                el: document.querySelector("[data-scroll-container]"),
                smooth: true,
                smoothMobile: false,
                resetNativeScroll: true
            });
        });

        // `useEffect`'s cleanup phase
        return () => {
            if (scroll) scroll.destroy();
        }
    });

    return (
        <main className="main" data-scroll-container>
            <Layout>
                <Component {...pageProps} />
            </Layout>
        </main>
    );
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement