What is the best way to update state inside a loop

Viewed 1284

Since setState works asynchronously, it does not update the state immediately. How do I update a state variable inside a loop.

The functionality is to validate multiple fields and to store if the field value is valid for a particular row index. However since the state changes do not reflect immediately, I am not receiving the desired output.

Please suggest the best way to handle this.

2 Answers

you are right.. setState works asynchronously. So there is no point calling it multiple times inside a loop or anywhere except at the end of your code block. Not a best practice either.

So what you can do is, have a copy of this state variable defined before your loop. Do whatever you wanna do with this variable inside the loop. At the end, you can just update your state with this updated variable for once.

This way you wouldn't have to use setState multiple times, also you can get the updated state inside the loop from the dummy variable.

Storing the data using ref(s) and updating the state at the end has solved the issue.

Related