setstate prevstate code example
Example 1: react prevstate
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
Example 2: prevstate in usestate
const [prevState, setState] = React.useState([]);
setState(prevState => [...prevState, 'somedata'] );
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: this.setstate prevstate
this.setState(prevState => ({ n: !prevState.n }))
Example 5: how to use setstate
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 (
{this.state.count}
)
}
}
Example 6: prevstate in react
handleClick() {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}