How to get the previous props or state in React?
In React class components, we had the
componentDidUpdate method, which provided the previous prop and state arguments. Now, with functional components, we have effects. In order to accomplish saving the previous state and prop values, we can store them to a ref. Refs do not have to be a DOM object.
usePrevious stores the value to the ref, but the
useEffect doesn’t run until the component is rendered. So the current value is returned, and it is stored for next time.
Then, in the component, you can use
usePrevious and pass it the value you want to keep track of.