You can access the previous state of properties or state in React Hooks by implementing a custom hook - in this example I’ve called it usePrevious
.
import { useEffect, useRef } from ‘react’;
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export default usePrevious;
This uses the out-of-the-box useRef hook to compare any property that’s passed into the function against its previously stored value.
We can import this usePrevious
hook into any component:
import usePrevious from ‘javascript/utils/hooks/use-previous';
Then we can get any previous value for a prop or piece of state by passing it into our usePrevious hook:
const prevFetchFilters = usePrevious(fetchFilters);
In this example I want to get the previous state of the fetchFilters
object, which contains a bunch of filters applied to a video listing, to see if any filters have been changed.
I can then comparing the previous state of the fetchFilters
object against its current state, using the package deep-equal
(https://www.npmjs.com/package/deep-equal), like:
!deepEqual(prevFetchFilters, fetchFilters);