Open In App

Is setState() method async ?

Last Updated : 28 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The React setState is asynchronous method. It has the ability to manage and update component state. However, there remains some confusion and debate regarding whether the setState() method is asynchronous or not. In this article, we’ll dive into this topic and shed light on how the setState() method behaves.

Prerequisite:

Is setState() method async ?

In React, setState() is generally asynchronous. When you call setState(), React schedules an update to the component’s state. This means that React doesn’t immediately apply the state change. Instead, it queues the update and batches multiple updates for better performance.

Why setState is asynchronous ?

React sets its state asynchronously because it can result in an expensive operation. Making it synchronous might leave the browser unresponsive. Asynchronous setState calls are batched to provide a better user experience and performance.

setState() async Issue:

If you’re using ReactJs, then you’re likely familiar with the setState method. This function is used to update the state of a component, but it’s important to remember that setState is asynchronous. This can lead to tricky debugging issues in your code.

setState async Example:

This example demonstrates the async behaviour of setState method.

Javascript




import React from 'react';
 
class App extends React.Component {
    constructor() {
        super();
 
        this.state = {
            value: '',
        };
    }
 
    render() {
        return (
            <div>
                <h2>GeeksforGeeks</h2>
                <form>
                    <label>
                        Input Field:-
                        <input
                            value={this.state.value}
                            onChange={(e) => {
                                console.log('Initial value:- ', this.state.value);
                                this.setState({ value: e.target.value });
                                console.log('Final value:- ', this.state.value);
                            }}
                        />
                    </label>
                </form>
            </div>
        );
    }
}
 
export default App;


Output: Here you can see the initial value and the final value are the same. 

Ways to make setState() synchronous

While setState() operates asynchronously in React, there are ways to achieve synchronous behavior when necessary.

1. Using Callbacks:

setState() method allows an optional callback function that executes after the state update is completed. You can utilize this callback to perform actions that depend on the updated state.

2. Using componentDidUpdate():

React lifecycle methods, particularly componentDidUpdate(), can be used to execute code after a state update. This lifecycle method triggers after a component’s state or props change.

3. State Based on Previous State:

The setState() allows developers to update state based on its previous value. This approach is vital when sequential state updates depend on the current state’s values.

Example: Making setState Synchronous using Callback

This example demonstrate the synchronous behaviour of setstate using callback function.

Javascript




import React from 'react';
 
class App extends React.Component {
    constructor() {
        super();
 
        this.state = {
            value: '',
        };
    }
 
    render() {
        return (
            <div>
                <h2>GeeksforGeeks</h2>
                <form>
                    <label>
                        Input Field:-
                        <input
                            value={this.state.value}
                            onChange={(e) => {
                                console.log('Initial value:- ', this.state.value);
                                this.setState({ value: e.target.value }, () => {
                                    console.log('Final value:- ', this.state.value);
                                });
                            }}
                        />
                    </label>
                </form>
            </div>
        );
    }
}
 
export default App;


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads