Skip to content
Advertisement

How to set the state in react with a delay in a for loop

i want to set a state in react in a loop going from 0 to “last step” but the state has to be set with a delay in other words:

-click a button, after the delay the state is set to 0, again after the delay the state is set to previous state +1, once the state is equal to “last step” end.

i tried this but is not working

JavaScript

Advertisement

Answer

If the button starts a counter from 0 to lastStep, then you need more than useState:

Solution 1: states and effect

JavaScript

Solution 2: reducer

JavaScript

The code can be tested here.

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