JAVASCRIPT
Track Previous State or Props with usePrevious Hook
Implement a custom React hook, usePrevious, to store and access the previous value of any state or prop, useful for comparing current and past data in components.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
// The ref object is a generic container whose .current property is mutable ...
// ... and can hold any value, similar to an instance field on a class
const ref = useRef();
// Store current value in ref on *every* render
useEffect(() => {
ref.current = value;
});
// Return previous value (happens before update in useEffect)
return ref.current;
}
/*
// Example Usage:
import React, { useState } from 'react';
function CounterWithPrevious() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default CounterWithPrevious;
*/
export default usePrevious;
How it works: The usePrevious custom hook provides a simple way to store and retrieve the previous value of any state or prop. It uses useRef to maintain a mutable reference and useEffect to update this reference *after* each render. This means that when the component re-renders, 'ref.current' still holds the value from the *previous* render cycle, enabling easy comparison or tracking. A commented example demonstrates its usage.