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// Correct
2this.setState(function(state, props) {
3 return {
4 counter: state.counter + props.increment
5 };
6});
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
1You have to use setState() for updating state in React
2{
3 hasBeenClicked: false,
4 currentTheme: 'blue',
5}
6
7setState({
8 hasBeenClicked: true
9});
10