state define in react code example
Example 1: state with react functions
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 2: change state in react
import React, {Component} from 'react';
class ButtonCounter extends Component {
constructor() {
super()
// initial state has count set at 0
this.state = {
count: 0
}
}
handleClick = () => {
// when handleClick is called, newCount is set to whatever this.state.count is plus 1 PRIOR to calling this.setState
let newCount = this.state.count + 1
this.setState({
count: newCount
})
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
)
}
}
export default ButtonCounter