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}
1import React, {Component} from 'react';
2
3class ButtonCounter extends Component {
4 constructor() {
5 super()
6 // initial state has count set at 0
7 this.state = {
8 count: 0
9 }
10 }
11
12 handleClick = () => {
13 // when handleClick is called, newCount is set to whatever this.state.count is plus 1 PRIOR to calling this.setState
14 let newCount = this.state.count + 1
15 this.setState({
16 count: newCount
17 })
18 }
19
20 render() {
21 return (
22 <div>
23 <h1>{this.state.count}</h1>
24 <button onClick={this.handleClick}>Click Me</button>
25 </div>
26 )
27 }
28}
29
30export default ButtonCounter
31
1 const [a, b] = React.useState(['hi','world']);
2 const dup = [...a]; //won't work without spread operator
3 b(dup);
1//initial state
2const [state, setState] = useState(0)
3//change state
4setState(1)
5//change state with prev state value
6setState((prevState) => {prevState + 2}) // 3