JAVASCRIPT
Custom Hook: usePrevious for Accessing Previous State/Prop
Build a usePrevious React hook to store and retrieve the previous value of any state or prop, enabling comparisons and handling value changes over time.
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 ? 'N/A' : prevCount}</p>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// <button onClick={() => setCount(count - 1)}>Decrement</button>
// </div>
// );
// }
How it works: The `usePrevious` hook stores the *previous* value of a given state or prop. It uses a `useRef` to maintain a mutable reference that persists across renders. An `useEffect` updates this ref with the current `value` *after* the render, ensuring that `ref.current` always holds the value from the *previous* render. This is extremely useful for comparing current and past values to trigger specific side effects.