useeffect previous state

Solutions on MaxInterview for useeffect previous state by the best coders in the world

showing results for - "useeffect previous state"
Neele
13 Aug 2018
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}