Home > database >  Race condition being set up by React.StrictMode double firing functions
Race condition being set up by React.StrictMode double firing functions

Time:11-28

I think I understand why React.StrictMode causes functions to be called twice. However, I have a useEffect that loads data from my api:

useEffect(() => {
  async function fetchData() {
    const data = await getData();
    setData(data);
  }

  fetchData();
}, []);

In my getData() function I call a maintenance script cullRecords() that cleans up my data by deleting records over a certain age before returning the data:

async function getData(){
  let results = await apiCall();
  cullRecords(results);
  return results;
}

Here's the rub: React.StrictMode fires the getData() function twice, loading up the apiCall() twice and firing the cullRecords() twice. However, by the time the second cullRecords() subscript fires, my API throws an error because those records are already gone.

While it's not the end of the world, I'm curious if I'm doing something wrong, or if this is just a fringe case, and not to worry about it.

CodePudding user response:

You can read through here also: https://beta.reactjs.org/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development

The same issue can occur if the user leaves/visits a route quickly for example (which is what development mode is simulating here). It might not be the the best approach to call a backend maintenance script when a UI component is being rendered.

CodePudding user response:

As per the race condition happening on APIs, it’s useful to implement debouncing methods as it’s explaned below.

The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called.

You can either use debouncing on either server-side or client side as they have pretty similar implementation.

  • Related