how to use setstate in react code example
Example 1: state with react functions
import React, { useState } from 'react';
function Example() {
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({
'isActive' : !this.state.isActive,
});
}
Example 4: react lifecycle example
class Test extends React.Component {
constructor() {
console.log('Constructor')
super();
this.state = {
count: 0
};
}
componentDidMount() {
console.log("component did mount");
}
componentDidUpdate() {
console.log("component did update");
}
onClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log("render");
return (
<div>
Hello Test
<button onClick={this.onClick}>
{this.state.count}
</button>
</div>
);
}
}
Example 5: setstate in react
Functional Component
const [counter, setCounter] = useState(0);
setCouter(counter + 1);
Example 6: react setState
this.setState({
date: new Date()
});