0
useEffect(() => {
    function initDashboardData() {
      console.count("initDashboardData");
      void dispatch(getDatabasesList());
      void dispatch(getUserConfig());
      void dispatch(
        getHistoricalData({ startTimestamp: getDateXDaysAgo(14, new Date()), endTimestamp: new Date() })
      );
    }

    void initDashboardData();
  }, [dispatch]);

All the actions (getDatabasesList, getUserConfig, etc..) are Redux createAsyncThunk actions that call an API.

When the component renders this function is called around five times, create 5 network calls.

How do you prevent multiple network calls from happening using dispatch w/ useEffect?

GN.
  • 8,672
  • 10
  • 61
  • 126
  • This might help: https://stackoverflow.com/questions/72301308/react-redux-useeffect-with-dispatch-fired-multiple-times – kazmi066 Dec 21 '22 at 04:12
  • Check how many times it gets called without dispatch. Just `[]`. If that's one, maybe log dispatch to see why its changing so much – Rajesh Dec 21 '22 at 04:13

1 Answers1

0

To prevent multiple calls of the function you could use a useRef hook's help, like so:

const dataLoadedFlag = useRef(false);

useEffect(() => {
    function initDashboardData() {
      // dispatch your stuff...
      dataLoadedFlag.current = true;
    }

    if (!dataLoadedFlag.current) {
      initDashboardData();
    }
  }, [dispatch]);
Greg Motyl
  • 2,478
  • 17
  • 31