0

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.

Trees4theForest
  • 1,267
  • 2
  • 18
  • 48
  • You can use ref to fire the effect only once. It kind of look like your `cullRecords` is doing something wrong – Konrad Nov 27 '22 at 23:44
  • Does this answer your question? [useEffect is running twice on mount in React](https://stackoverflow.com/questions/72238175/useeffect-is-running-twice-on-mount-in-react) – Youssouf Oumar Nov 29 '22 at 18:10
  • *"if remounting breaks the logic of your application, this usually uncovers existing bugs. From the user’s perspective, visiting a page shouldn’t be different from visiting it, clicking a link, and then pressing Back."* See the answer in the above thread, please. It might help you. – Youssouf Oumar Nov 29 '22 at 18:12
  • I get WHY it's running twice ( already linked to that ) it's a question of whether this is a bad idea... – Trees4theForest Nov 30 '22 at 05:43

2 Answers2

2

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.

strada
  • 942
  • 9
  • 18
1

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.

Erhan Yaşar
  • 847
  • 1
  • 9
  • 25