1

I am wondering how to implement scroll-triggered animations in Next.Js 13 properly.

I have tried to use a scroll-triggered animation library like AOS, but in order for it to work, it needs to be initialized inside a useEffect hook, which requires client-side rendering. Now all of that would be ok, if I was only using it for one component (and only for that component declaring client-side rendering via 'use client'), but that is not an option, since I want to make AOS accessible across my whole application, so that all components and parts of the page can consume it, and that, therefore, means, if Im getting this right, that everything would use client-side rendering (since I am declaring at the root (in order to be able to use useEffect)), which is not what I want.

Is there a better way of implementing this or am I just understanding this all the wrong way? I am new to Next.Js so I'm sorry if this question is more on the 'stupid' side, but I couldn't find, or figure out an answer so I decided to ask it over here. I will be happy to hear your answers. :)

Gal Povsod
  • 101
  • 1
  • 7
  • 1
    Hey Gal, so you are correct on trying to avoid using "use client" and move on... For you specific scenario I can see 2 ways, one could be simple but requires testing another one should work as well but needs a little bit more coding. 1- You can try to lazy load AOS by creating a dummy component that returns a Fragment for example and then importing this dude on the top but lazy load it, so you'll end up having a good performance gain overall. Needs further testing – Ogrodev Mar 01 '23 at 21:46
  • 1
    2- Another approach would be to create a custom hook for this implementation and use the logic for the AOS (which I do not know about sorry) anywhere you want to. – Ogrodev Mar 01 '23 at 21:48
  • @PedroMendes Thank you so much for the suggestion. I will try to implement one of theese aproaches and see how it goes! :) – Gal Povsod Mar 02 '23 at 05:48

1 Answers1

1

I was able to make it work by doing this:

  1. Created a reusable component named AOS.jsx as below:
import { useEffect } from 'react';

import AOS from "aos";
import "aos/dist/aos.css";

export default function AOSComponent({
    children,
}: {
    children: React.ReactNode
}) {
    useEffect(() => {
        AOS.init()
    }, [])

    return <>{children}</>
}
  1. On each page 'client' where I need the AOS features, I wrap the page elements within it as below:

'use client'
...
import AOSComponent from '@/components/AOS';

export default function Home() {
  return (
    <AOSComponent>
      <div>
        Homepage
      </div>
    </AOSComponent>
  )
}
yorme
  • 31
  • 2