JAVASCRIPT
Track Previous State or Prop with `usePrevious`
Develop a `usePrevious` React hook to access the previous value of any state or prop, enabling comparisons and logic based on changes over time in your components.
import { useEffect, useRef } 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: {count}</p>
<p>Previous Count: {prevCount !== undefined ? prevCount : 'N/A'}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
*/
How it works: The `usePrevious` hook utilizes a `useRef` to store the value from the previous render. In the `useEffect` hook, `ref.current` is updated with the `value` *after* the render has committed. This means that on the *next* render, `ref.current` will hold the value that `value` had during the *current* render. This pattern is incredibly useful for comparing a current prop or state with its immediate prior value, for example, to detect changes or trigger side effects conditionally.