Why using the setState method in React doesn’t mutate the state immediately?

The reason is setState is asynchronous, you can’t expect the updated state just after the setState, if you want to check the value use a callback method. Pass a method as a callback that will be get executed after the setState completes its task.

Why setState is asynchronous?

This is because setState alters the state and causes re-rendering. It can be an expensive operation and making it synchronous might leave the browser unresponsive. Thus, the setState calls are asynchronous as well as batched for better User experience and performance

How to use the setState with a callback?

  1. In React class-based components, to check the updated state value just after the setState, use a callback method like this:
this.setState({ key: value }, () => {
console.log('updated state value', this.state.key)

2. In a functional component (using useState hook), checking the updated state in a useEfftect hook:

const [beerCount, setBeerCount] = useState(0);

useEffect(() => {
console.log("count updated! this is run after update!");
}, [beerCount]); // run whenever beerCount is changed




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Latvian Numbers And Counting — An Easy #1 Guide

Map vs. Set vs. Object in Javascript

Getting Started With React & Socket.io

jb update doesn’t download the update

Hoisting in JavaScript: A Brief But Comprehensive Guide

React App — Final Project

Nepali Pronouns With Examples — An Easy 2021 Guide

Embedding jQuery QueryBuilder in flutter/flutter-web

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dung.ntp Dung.ntp

Dung.ntp Dung.ntp

More from Medium

What is this React Hooks

Introduction to React Hooks

How to pass state or data in react-router v6

How to pass state or data in react-router v6