PrevState does not update state value immediately in React JS

Viewed 1002

I am trying to update state value immediately with the use of prevState but value does not change. I know seState is asycnc function but If I use prevState, should not be update immediately? Where I do the mistake?

   count: 0
    this.setState((prevState) => ({
      count: prevState +1
    }));

    console.log(this.state.count+" count")
3 Answers

As you know setState is async. But also learn if you pass callback in setstate then you need to call prevState.something as something is your state. SO basically you need to do this:

this.setState(
      (prevState) => ({
        count: prevState.count + 1
      }),
      () => {
        console.log(this.state.count + " count");
      }
    );

Here is POC:

import React from "react";
import "./styles.css";

class Test extends React.Component {
  state = {
    count: 0
  };

  handleClick = () => {
    this.setState(
      (prevState) => ({
        count: prevState.count + 1
      }),
      () => {
        console.log(this.state.count + " count");
      }
    );
  };

  render() {
    return (
      <>
        {this.state.count}
        <button onClick={this.handleClick}>Click </button>
      </>
    );
  }
}

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Test />
    </div>
  );
}


Here is the demo: https://codesandbox.io/s/serene-beaver-cu4bl?file=/src/App.js:0-596

Ok You have to understand the following thing

function foo() {
  this.setState((prevState) => ({
    count: prevState + 1,
  }));
}

//call function first and then log
foo()
console.log(count) // here you will get your answer

Remember any number of this.setState statement in one parent function will execute after the parent function ends

Related