0

I have a landing page and some about, faq, tnc, etc pages. When I navigate (using react-router v6) from landing page to another and come back, the useEffect executes even though I have given empty dependency array.

useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.type = "module";
        script.src = "scripts/animation.script.js";
        document.body.appendChild(script);
        console.log("running");
      }, []);

I also tried passing a dependency which do not change like this..

const doNotLoadLandingAnimation = true;
    useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.type = "module";
        script.src = "scripts/animation.script.js";
        document.body.appendChild(script);
        console.log("running");
      }, [doNotLoadLandingAnimation]);

But still.. useEffect executes everytime the page is visited.

Abhijeet
  • 75
  • 2
  • 9
  • 1
    Thats pretty normal, useEffect with empty deps array will be executed once on component mount and will not reexecute after rerender, but your case i guess is component is unmounted and mounted back again later when you navigate from PageA to PageB. So this part works in that way by design. – Sergey Sosunov Jan 13 '23 at 18:17
  • useEffect with an empty dependency array will run every time the component is mounted. Not sure exactly what your script is doing, but you could possibly add some logic to your `useEffect` that checks if the script is already added to the body, and if not, add the script. – Rico Hancock Jan 13 '23 at 18:18
  • Does this answer your question? [Adding script tag to React/JSX](https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx) – Sergey Sosunov Jan 13 '23 at 18:29

0 Answers0