JAVASCRIPT
Tracking Previous State or Props with the `usePrevious` Hook
Implement a `usePrevious` React hook to easily access the previous value of any state or prop, useful for comparing current and past values in `useEffect` or other logic.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
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 allows you to store and retrieve the value that a variable had on the previous render cycle. It leverages the `useRef` hook to create a mutable reference that persists across renders without causing re-renders itself. Inside a `useEffect` hook, the `ref.current` is updated with the `value` after every render, making the "previous" value available on the subsequent render.