3

I have a useEffect which initializes wowjs in a component like so:

import WOW from "wowjs";

const HomePage = () => {

useEffect(() => {
        const wow = new WOW.WOW({
        boxClass: "wow",
        animateClass: "animated",
        offset: 0,
        mobile: false,
        live: true,
        scrollContainer: null
      });
      wow.init();
    }, []);

  return (
    <div>
      ....
    </div>
  )
}

I want this useEffect in many components so that the wowjs animations can run on every route change. How do i avoid repeating this code in my reactjs project?

Sushmit Sagar
  • 1,412
  • 2
  • 13
  • 27

1 Answers1

9

As RTW mentionned in his comment, you could use a HOC to centralize this code.

But as it seems you have been already hooked by hooks, I would suggest to put this code in a custom useWow hook and just call this hook in every component where you may need it.

const useWow = () => {

  const initWow = () => {
    const wow = new WOW.WOW({
        boxClass: "wow",
        animateClass: "animated",
        offset: 0,
        mobile: false,
        live: true,
        scrollContainer: null
      });
    wow.init();
  }

  return { initWow }
}

And then in your component

const { initWow } = useWow()

useEffect(() => {
 initWow();
}, [])
Arnaud Christ
  • 3,440
  • 3
  • 24
  • 33