1const [prevState, setState] = React.useState([]);
2
3setState(prevState => [...prevState, 'somedata'] );
1const Component = (props) => {
2 const {receiveAmount, sendAmount } = props
3
4// declare usePrevious hook
5 const usePrevious = (value) => {
6 const ref = useRef();
7 useEffect(() => {
8 ref.current = value;
9 });
10 return ref.current;
11 }
12
13// call usePrevious hook on component state variables to store previousState
14 const prevAmount = usePrevious({receiveAmount, sendAmount});
15
16 // useEffect hook to detect change of state variables
17 useEffect(() => {
18 if(prevAmount.receiveAmount !== receiveAmount) {
19
20 // process here
21 }
22 if(prevAmount.sendAmount !== sendAmount) {
23
24 // process here
25 }
26 }, [receiveAmount, sendAmount])
27}
1import React, { useState } from "react";
2import ReactDOM from "react-dom";
3
4function Counter() {
5 const [count, setCount] = useState(0);
6
7 return (
8 <div>
9 <h1>{count}</h1>
10 <button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
11 Delayed Counter (basic)
12 </button>
13 <button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
14 Delayed Counter (functional)
15 </button>
16 <button onClick={() => setCount(count + 1)}>Immediate Counter</button>
17 </div>
18 );
19}
20
21const rootElement = document.getElementById("root");
22ReactDOM.render(<Counter />, rootElement);
23