JAVASCRIPT
Track Previous Prop or State Value with `usePrevious` Hook
Learn to create a custom React hook, `usePrevious`, to easily track and access the previous value of any prop or state variable in your components.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
How it works: This custom React hook uses `useRef` to store the previous value of a state or prop. Inside a `useEffect` hook, the current value is stored in the ref after every render where the value changes. The ref's `current` property is then returned, effectively giving you access to the value from the *previous* render cycle, which is useful for comparing changes.