0

There are two different types of components, each modifying the value of num continuously when the button is clicked, why the output of the two components is different.

Class Component

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      num: 0
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    setTimeout(() => {
      this.setState({
        num: this.state.num + 1
      });
      this.setState({
        num: this.state.num + 1
      });
      this.setState({
        num: this.state.num + 1
      });
      console.log(this.state.num); // 0, 3, 6...
    }, 0);
  }

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

Function Component

export default function App() {
  const [num, setNum] = useState(0);

  const handleClick = () => {
    setTimeout(() => {
      setNum(num + 1);
      setNum(num + 1);
      setNum(num + 1);
      console.log(num); // 0, 1, 2, 3...
    }, 1000);
  };

  return <button onClick={handleClick}>{num}</button>;
}
ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • `this` is a mutable object, and setting state will sometimes (but not always) modify `this.state` by the time you hit your log statement. `num` is a local const and can never change. In both cases, you should not write code that relies on the value changing synchronously. You can instead use the function version of set state to get passed the latest value. – Nicholas Tower Feb 23 '22 at 01:44
  • cause in class component consequent renders will will refer to the latest value in the state object vs referring to a particular render value vs in hooks every render refers to the state object exclusive to that particular render (kind of a constant for that particular render exclusively) vs referring to the latest state value at the tine. hope this helps – Anuj Feb 23 '22 at 01:51

0 Answers0