1class App extends React.Component {
2
3state = { count: 0 }
4
5handleIncrement = () => {
6 this.setState({ count: this.state.count + 1 })
7}
8
9handleDecrement = () => {
10 this.setState({ count: this.state.count - 1 })
11}
12 render() {
13 return (
14 <div>
15 <div>
16 {this.state.count}
17 </div>
18 <button onClick={this.handleIncrement}>Increment by 1</button>
19 <button onClick={this.handleDecrement}>Decrement by 1</button>
20 </div>
21 )
22 }
23}
1class Example extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 count: 0
6 };
7 }
8
9 render() {
10 return (
11 <div>
12 <p>You clicked {this.state.count} times</p>
13 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
14 Click me
15 </button>
16 </div>
17 );
18 }
19}
1Functional Component
2const [counter, setCounter] = useState(0);
3
4setCouter(counter + 1);
1incrementCount() {
2 // Note: this will *not* work as intended.
3 this.setState({count: this.state.count + 1});
4}
5
6handleSomething() {
7 // Let's say `this.state.count` starts at 0.
8 this.incrementCount();
9 this.incrementCount();
10 this.incrementCount();
11 // When React re-renders the component, `this.state.count` will be 1, but you expected 3.
12
13 // This is because `incrementCount()` function above reads from `this.state.count`,
14 // but React doesn't update `this.state.count` until the component is re-rendered.
15 // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
16
17 // The fix is described below!
18}