JAVASCRIPT
Get the Previous Value of State or Prop with `usePrevious`
Create a custom React `usePrevious` hook to easily track and access the prior value of any state variable or prop between renders.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
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 previous value of any given state or prop. It leverages `useRef` to hold the value from the *previous* render. In the `useEffect` callback, the `ref.current` is updated with the `current` value *after* the render, ensuring that on the next render, `ref.current` holds the value from the render just completed.