Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling setState in a loop only updates state 1 time

Is there a reason that calling setSate() in a loop would prevent it from updating the state multiple times?

I have a very basic jsbin that highlights the problem I am seeing. There are two buttons. One updates the state's counter by 1. The other calls the underlying function of One in a loop -- which seemingly would update the state multiple times.

I know of several solutions to this problem but I want to make sure that I am understanding the underlying mechanism here first. Why can't setState be called in a loop? Do I have it coded awkwardly that is preventing the desired effect?

like image 869
adam-beck Avatar asked Feb 07 '16 01:02

adam-beck


People also ask

Can I call setState in a loop?

As we know that we can't setState in a loop, I took a different approach by running the task recursively.

Can you call setState multiple times?

If you have ever tried to set a state variable multiple times in a row in a React component, you may have been surprised to find that it didn't quite work. It would be reasonable to expect that, every time you click the “Increment Twice” button, count will increase by two.

Why setState is not updating immediately?

setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.

What is the problem with updating state directly instead of setState ()?

When you directly update the state, it does not change this. state immediately. Instead, it creates a pending state transition, and accessing it after calling this method will only return the present value. You will lose control of the state across all components.


1 Answers

From the React Docs:

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

Basically, don't call setState in a loop. What's happening here is exactly what the docs are referring to: this.state is returning the previous value, as the pending state update has not been applied yet.

like image 187
rossipedia Avatar answered Sep 26 '22 02:09

rossipedia