JAVASCRIPT
Track Previous State with usePrevious Hook
Develop a `usePrevious` React hook to easily access the previous value of a prop or state variable, useful for comparing current and past states.
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}, Previous: {prevCount}</p>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// </div>
// );
// }
How it works: The `usePrevious` hook provides a simple way to store and retrieve the value that a state or prop had on the *previous* render cycle. It leverages `useRef` to maintain a mutable reference to the value. The `useEffect` hook ensures that `ref.current` is updated to the `value` after every render, making the previous value available on the subsequent render. This is ideal for scenarios requiring comparison between current and past states.