usePreviousState
A hook that returns the previous value of a state or prop.
The usePreviousState hook stores and returns the previous value of any state variable or prop. On the first render it returns undefined.
Demo
Previous State
0
Previous: undefined
Current: Alice → Previous: undefined
Source Code
Copy this code into src/hooks/usePreviousState.ts:
import { useEffect, useRef } from "react";
export const usePreviousState = <T>(value: T): T | undefined => {
const ref = useRef<T | undefined>(undefined);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};Usage
import { usePreviousState } from '@/hooks/usePreviousState';
const Counter = () => {
const [count, setCount] = useState(0);
const prevCount = usePreviousState(count);
return (
<div>
<p>Current: {count}</p>
<p>Previous: {prevCount ?? 'none'}</p>
<button onClick={() => setCount((c) => c + 1)}>+1</button>
</div>
);
};API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | The current value to track |
Return Value
| Type | Description |
|---|---|
T | undefined | The value from the previous render, or undefined on first render |