usePrevious Hook
December 21, 2025
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;
}
How It Works
- A ref persists across renders and stores the previous value.
- In each render, useEffect updates the ref after the component finishes rendering.
- So ref.current always holds the value from the previous render.
Example Usage
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>
);
}
Use Cases
- Compare current vs previous state for conditional logic
- Track prop changes over time
- Animate UI transitions based on change direction
- Debugging component updates
Notes
- Returns undefined on first render (no previous value yet).
- Make sure to handle undefined in your logic.
- Works for any type T: string, number, object, etc.
The usePrevious hook is a helpful tool to observe how state or props evolve — giving your components memory of the past.