how to setstate 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: set state
class App extends React.Component {
state = { count: 0 }
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
}
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
}
render() {
return (
<div>
<div>
{this.state.count}
</div>
<button onClick={this.handleIncrement}>Increment by 1</button>
<button onClick={this.handleDecrement}>Decrement by 1</button>
</div>
)
}
}
Example 3: setstate react js
constructor(props) {
super(props);
this.state = {
isActive: true,
};
}
checkStatus = () => {
this.setState({ // use this function
'isActive' : !this.state.isActive,
});
}
Example 4: setstate in react
Functional Component
const [counter, setCounter] = useState(0);
setCouter(counter + 1);
Example 5: react setState
this.setState({
date: new Date()
});
Example 6: react setState
incrementCount() {
// Note: this will *not* work as intended.
this.setState({count: this.state.count + 1});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.
// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
// The fix is described below!
}