Skip to content
Advertisement

Prevent infinite loop in useEffect when setting state

I am currently building a scheduling app. If a user selects two dates, I am attempting to select all date blocks between the two selected dates in the calendar as well. I am able to achieve this, but it causes my useEffect to fire into an infinite loop because I have state as a dependency in my useEffect where I am setting state. I am unsure of the best method to prevent the infinite loop behavior. The useEffect in question is the bottom one. My code is as follows:

JavaScript

attached is a code sandbox for debugging and to show the behavior I am currently talking about. Select two separate dates that are greater than today and you will see all the dates in between are selected, but the app goes into a loop https://codesandbox.io/s/dawn-snow-03r59?file=/src/App.js:301-4499

Advertisement

Answer

If your useEffect depends on a variable that you’re updating on the same useEffect there will always be the re-render and cause a loop.

If you want it to execute only once, you should remove the data variable from the useEffect dependency array.

But if you really wanna mutate the state every time that the data variable changes, my recommendation is to create another state for the mutated data.

For example setFormattedData would not change the data itself, but you would still have a state for this data in the format that you want.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement