reactjs|June 28, 2020|3 min read

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

TL;DR

React's setState is asynchronous, so reading state immediately after calling it returns stale values; use the callback form of setState that receives prevState to ensure correct state updates.

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS setState is Asynchronous

setState() method in ReactJS class components is asynchronous in nature. Lets understand this with the help of an example.

Example: Lets create a counter field and have two Plus and Minus buttons for incrementing and decrementing count. And, we will maintain counter in component’s state.

Example showing Asynchronous behavior of setState

import React, { Component } from 'react'

class MyApp extends Component {
    state = {
        counter: 0
    }
    minusHandle = () => {
        console.log('minus debug 1', this.state.counter);
        
        this.setState({counter: this.state.counter - 1});
        this.setState({counter: this.state.counter - 1});

        console.log('minus debug 2', this.state.counter);
    }

    plusHandle = () => {
        console.log('plus debug 1', this.state.counter);
        
        this.setState({counter: this.state.counter + 1});
        this.setState({counter: this.state.counter + 1});

        console.log('plus debug 2', this.state.counter);
    }
    render() {
        return (
            <React.Fragment>
                <button type="button" onClick={this.minusHandle}>
                    Minus
                </button>
                count : {this.state.counter}
                <button type="button" onClick={this.plusHandle}>
                    Plus
                </button>
            </React.Fragment>
        )
    }
}

class App extends Component {
    render() {
        return <React.Fragment>
            <MyApp />
        </React.Fragment>
    }
}

export default App;

Lets have a look at the output:

# web
[Minus] Count: 0 [Plus]

# click on [Plus] button
## web
[Minus] Count: 1 [Plus]
## Console log
plus debug 1 0
plus debug 2 0

# click on [Plus] button
## web
[Minus] Count: 2 [Plus]
## Console log
plus debug 1 1
plus debug 2 1

If you notice, both console.log statements prints count: 0, as they executed before setState() executed. Since, setStaate is asynchronous. Also we are calling setState() twice. Even then, counter is increased by 1 only. Because both setState() calls are aware of one state only at the time of start.

Similarly if I click on Minus button, same kind of behavior will happen. So, the important thing to note is that you can not rely on setState() for calculating next state.

Fix this

setState() has another variant, which accepts a function. It receives previous state and current props as argument. See complete example. I have modified only plusHandle()

import React, { Component } from 'react'

class MyApp extends Component {
    state = {
        counter: 0
    }
    minusHandle = () => {
        console.log('minus debug 1', this.state.counter);
        
        this.setState({counter: this.state.counter - 1});
        this.setState({counter: this.state.counter - 1});

        console.log('minus debug 2', this.state.counter);
    }

    plusHandle = () => {
        console.log('plus debug 1', this.state.counter);
        
        this.setState(
            (state, props) => {
                return { counter: state.counter + 1 };
            }
        );
        this.setState(
            (state, props) => {
                return { counter: state.counter + 1 };
            }
        );

        console.log('plus debug 2', this.state.counter);
    }
    render() {
        return (
            <React.Fragment>
                <button type="button" onClick={this.minusHandle}>
                    Minus
                </button>
                count : {this.state.counter}
                <button type="button" onClick={this.plusHandle}>
                    Plus
                </button>
            </React.Fragment>
        )
    }
}

class App extends Component {
    render() {
        return <React.Fragment>
            <MyApp />
        </React.Fragment>
    }
}

export default App;

Lets take a look at the output, when I click on Plus button

# initial web view
[Minus] Count: 0 [Plus]

# click on [Plus] button
## web
[Minus] Count: 2 [Plus]

## console
plug debug 1 0
plug debug 2 0

# click again on [Plus] button
## web
[Minus] Count: 4 [Plus]

## console
plug debug 1 2
plug debug 2 2

Notice the magic. State is updated as many times you have called setState(). But, the behavior of setState() is still asynchronous, i.e. debug statements executed before setState()

Related Posts

ReactJS - How to restrict data type for different kind of data

ReactJS - How to restrict data type for different kind of data

Introduction Javascript is not a strict type language. We can use a variable to…

ReactJS - Basic Form Handling and Form submission

ReactJS - Basic Form Handling and Form submission

Introduction Lets take a look at how forms are being handled in ReactJS. We will…

ReactJS - How to create ReactJS components

ReactJS - How to create ReactJS components

Introduction In this post, we will talk about basic of how to create components…

ReactJS - How to pass method to component and how to pass arguments to method

ReactJS - How to pass method to component and how to pass arguments to method

Introduction In the ReactJS project, you are having aa parent component and a…

ReactJS - 3 ways to Import components in ReactJS

ReactJS - 3 ways to Import components in ReactJS

Introduction In this post, we will discuss 3 different ways to import a…

ReactJS - How to use conditionals in render JSX

ReactJS - How to use conditionals in render JSX

Introduction In this post, I will show several ways to use conditionals while…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…