Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next js routing triggers useEffect

I'm trying to fetch data inside useEffect using axios but it fetches the data everytime I change the page. Is there a way to not trigger useEffect when changing the page? I tried to use shawllow push but it didn't work. I can't fetch on server side because I use next/router inside axios interceptor.

   import { useRouter } from 'next/router';
   const router = useRouter();
   router.push('/', '/', { shallow: true })

With the above code, it will trigger useEffect when switching routes.

  useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
  }, []);
like image 432
user8991667 Avatar asked Oct 16 '25 03:10

user8991667


1 Answers

If you have something in useEffect that you only want to run once, add an empty array as the dependency array.

Example:

  useEffect(() => {
      // your axios fetch here
  }, []);

Empty array as the dependencies means the effect is run once. If you don't specify the dependencies, the effect will run after every render.

like image 180
Olavi Avatar answered Oct 18 '25 15:10

Olavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!