prevstate in react hooks 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: prevstate in react
handleClick() {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
Example 4: when to use previous state in useState
import React, { useState } from "react";
import ReactDOM from "react-dom";
function Counter() {
const [count, setCount] = useState(0);
return (
{count}
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);