Leo Fabrikant
Leo Fabrikant

Reputation: 735

How does React Redux handle successive changes in a loop

If I have a loop that dispatches a redux action on each cycle, how do React and Redux handle updating connected components? If each redux action would individually cause a reRender of certain components, and assuming each cycle updates the state to have new values, do those components reRender each time around the loop?

Do a component's update lifecycle hooks run synchronously in the loop, or do React / Redux batch the expected changes somewhere and then update once after the loop has finished?

Based on my experience just now, it appears there is some kind of batching going on, because a component seems to be updating only at the end of the loop with all of the changes registering at once.

Any ideas on how to get around this? Meaning I want a connected component's "componentWillReceiveProps" method to run each time a redux action makes its way through the reducers and changes the state.

Upvotes: 1

Views: 1229

Answers (3)

Leo Fabrikant
Leo Fabrikant

Reputation: 735

It does appear that React updates are asynchronous and, at least for changes caused by updating redux stores, changes are batched. It would be interesting to see what would happen with a loop running setState for that component. Regardless, the solution was to make the loop asynchronous such as the following (suggestions on clearer / more efficient ways to make an async loop would be appreciated):

const iterable = [...]

const asyncLoop = (i) => {
  if(!iterable[i]) return
  const cycle = new Promise (resolve=>{
      dispatchReduxAction(iterable[i])
      resolve(i+1)
  })
  cycle.then((j)=>{
    asyncLoop(j)
  })
}

asyncLoop(0)

Upvotes: 0

Shishir Arora
Shishir Arora

Reputation: 5923

Just for answer sake, else, above answer is right.
Run loop with a callback in setInterval, keeping some arbitrary interval time. The callback should increment the counter of loop and setState/dispatch-action

Upvotes: 0

Sagiv b.g
Sagiv b.g

Reputation: 31024

I wasn't sure about redux at first so i wrote my thoughts as a comment.
The more i thought about it the more i realize that we know the answer:
First of all, react's setState is async that's on thier DOCS

This form of setState() is also asynchronous, and multiple calls during the same cycle may be batched together.

But when you think about it, how can it not be?
Js has only 1 thread, this thread is so busy with your loop so it can't free it self to invoke the code like dispatch or setState etc.
When your loop is done, this is the time for all the "disptaching" and state settings to run, the amazing part here is that it can "remember" the context and scope of each variable and object, thanks to our good friend the closure.

Upvotes: 2

Related Questions