Track the previous value of a state or prop in React.
import { useEffect, useRef } from 'react';
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}In some scenarios, you might need to compare the current value of a state or prop with its previous value. React doesn’t store previous values by default — that’s where usePrevious comes in.
import { useEffect, useRef } from 'react';
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
function Counter() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<div>
<p>Current: {count}</p>
<p>Previous: {prevCount ?? 'N/A'}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
);
}
The usePrevious hook is a helpful tool to observe how state or props evolve — giving your components memory of the past.