3 Minute React : Secret behind setState

Vilva Athiban P B
2 min readJan 27, 2019

3 Minute React is a new series in which we will cover interesting and not so common thing in React. In this article we will see how to achieve synchronous behavior in setState and avoid batching of multiple setStates.

Link to the youtube tutorial:

In general, we don’t mutate the state in react and we use setState to change the state of the component. Look at the following example:

In the above piece of code, we have a component that displays the count from the state. It has two buttons — Batched setState and Synchronous setState.

The Batched setState button invokes batchedIncrement function which increases the count in the state by 1. Now lets add few more setState to the function as below:

Inspite of adding multiple setState in the function, the count is incremented only once because of batching. Here all the setState functions are batched into one and hence, the value is incremented only by 1.

Now lets consider a scenario where we need to increase the count based on the number of setState in a function. How do we avoid batching and achieve the same? The setState function holds a second form. Instead of accepting a object as an argument, it accepts a function which gets the currentState as the argument. Refer to the code below:

In the above piece of code, we have passed a function instead of object and hence, the count value is increased by 1 for each setState in the function. This avoids batching of setState and might come handy in few scenarios where the existing state values are used to calculate the new state values.

CodeSandbox link to play around the code : https://codesandbox.io/s/4rojjo4v27

Suggestions are welcome. Follow me in medium and subscribe to my youtube if you like the content.

Youtube: https://www.youtube.com/channel/UCFSQ3m4-hJ0izfsMUrAk7mw

Medium: https://medium.com/@vilvaathiban

Linkedin: https://www.linkedin.com/in/vilvaathiban/

See you in the next part of 3 minute React.

--

--

Vilva Athiban P B

9+ years of Experience in React-Redux / NodeJS / GraphQL / TypeScript. https://vilvaathiban.com