Search code examples
javascriptreactjssetstate

Regarding prevState callback in .setState()


Case1.

    handleRemovePlayer = id => {
        this.setState(prevState => {
            return {
                players: prevState.players.filter(player => player.id !== id)
            };
        });
    };

Case2.

    // Arrow Func: become Component instance
    incrementScore = () => {
        this.setState(prevState => ({
            score: this.state.score + 1
        }));
    };
    decrementScore = () => {
        if (this.state.score > 0) {
            this.setState(prevState => ({
                score: this.state.score - 1
            }));
        }
    };

In setState(), why case1 cannot use this.players.filter instead of prevState.player? Both case1 and 2 use the same prevState callback.. Can anyone explain precisely regarding prevState? Thanks in advance!


Solution

  • Currently, setState() is asynchronous inside event handlers.

    Let assume that- you updated your state and you want to check state is updated or not.

    for that you can use updater(callback) as 2nd argument to check updated state.

    like this -

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

    Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state ...for your reference setState in reactjs