0

my question seems to be quite simple. But in the code below, how is it possible to use "prevState" as function without coding the function ?

handleAddOne() {
    this.setState(prevState => {
      return {
        counter: prevState.counter + 1
      };
    });
  }

` Here you can see all the code in which handleAddOne() is include.

import React from "react";
import ReactDOM from "react-dom";

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
    this.handleAddOne = this.handleAddOne.bind(this);
  }
  handleAddOne() {
    this.setState(prevState => {
      return {
        counter: prevState.counter + 1
      };
    });
  }
  render() {
    return (
      <div>
        <div>Counter: {this.state.counter}</div>
        <button onClick={this.handleAddOne}>Add One</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

I didn't try anything special, just need explanation.

  • Can you please clarify your question? Are you asking why your code works and why it's possible to pass a function to `setState()`? Or are you asking how to achieve some type of functionality? – Nick Parsons Nov 29 '22 at 08:56

2 Answers2

0

How about using "React Hook" like "useState, useEffect()". it's can checked your value, and you can start function and setState also.

Louie
  • 1
  • 1
  • Thank you for your answer. Yes, but my purpose here is to know if prevState is a parameter of the function passed into setState, or the name of the function itself. – Edharad Nov 29 '22 at 10:02
0

I'm not sure if I understand your question properly because you DID code the function when you wrote:

prevState => {
  return {
    counter: prevState.counter + 1
  };
}

This is an arrow function definition. You can store it in a variable and call it later or pass it as an argument to another function without storing it; as you did with this.setState. You can read more about js arrow functions here. Also, this is a recursive function that calls itself, and you can read about it here.

Sin
  • 31
  • 8
  • Thank you for your answer it helped me. I didn't know what is "prevState", my purpose here is to know if prevState is a parameter of the function passed into setState, or the name of the function itself. – Edharad Nov 29 '22 at 09:59
  • @Edharad Glad I could help. `prevState` is the parameter of this arrow function. In other words, `setState` has a function as its parameter and this function has a single parameter called `prevstate`. the second function (which is the parameter of `setstate`) is an "Anonymous function" too and therefore has no name associated with it. You can read more about anonymous functions [here](https://www.javascripttutorial.net/javascript-anonymous-functions/). – Sin Nov 29 '22 at 11:20