JAVASCRIPT
Get the Previous Value of a Prop or State in React
Implement a custom `usePrevious` React hook to easily access the value a prop or state had on the previous render, useful for comparisons and conditional logic.
import { useRef, useEffect } from 'react';
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
export default usePrevious;
// 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</n>
</div>
);
}
*/
How it works: The `usePrevious` hook utilizes `useRef` to store the previous value. In a `useEffect` hook, `ref.current` is updated with the current `value` *after* the render cycle completes. This ensures that on any given render, `ref.current` holds the value from the *previous* render, while the component function itself sees the *current* `value`.