JAVASCRIPT
Track Previous State or Prop Values with usePrevious Hook
Learn to create a simple yet powerful React usePrevious hook to easily access the previous value of any state or prop, useful for comparing changes.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}); // No dependency array means it runs on every render
return ref.current;
}
// Example Usage:
// function Counter() {
// const [count, setCount] = useState(0);
// const prevCount = usePrevious(count);
// return (
// <div>
// <p>Current: {count}</p>
// <p>Previous: {prevCount !== undefined ? prevCount : 'N/A'}</p>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// </div>
// );
// }
How it works: The `usePrevious` hook provides a way to get the value of a prop or state from the previous render cycle. It uses a `useRef` to persist the value across renders without causing re-renders itself. The `useEffect` hook, which runs after every render, updates the ref's current value to the current `value` passed into the hook. On the subsequent render, the ref will contain the value from the *previous* render, making it excellent for comparing current and past states.