previous state useSTate code example
Example 1: prevstate in usestate
const [prevState, setState] = React.useState([]);
setState(prevState => [...prevState, 'somedata'] );
Example 2: usestate hook
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 3: useeffect previous state
const Component = (props) => {
const {receiveAmount, sendAmount } = props
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const prevAmount = usePrevious({receiveAmount, sendAmount});
useEffect(() => {
if(prevAmount.receiveAmount !== receiveAmount) {
}
if(prevAmount.sendAmount !== sendAmount) {
}
}, [receiveAmount, sendAmount])
}
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 (
<div>
<h1>{count}</h1>
<button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
Delayed Counter (basic)
</button>
<button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
Delayed Counter (functional)
</button>
<button onClick={() => setCount(count + 1)}>Immediate Counter</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);
Example 5: usestate access previous state
const [arrayOfObjs, handleObjSelection] = useState([]);
<button
onClick={selectedObj => handleObjSelection(
prevSelected => [...prevSelected, selectedObj],
))}
>