usePrevious
React state hook that returns the previous state as described in the React Docs
usePrevious accepts a value and returns the value from the previous render. On the initial render it returns undefined since there is no prior value. The hook stores the previous value in a ref and updates it after each render, giving you a snapshot of what the value was before the most recent change.
When to Use
- Comparing current and previous values to trigger animations, transitions, or conditional logic
- Detecting direction of change (e.g., whether a counter increased or decreased)
- Implementing undo functionality or displaying “changed from X to Y” indicators
Notes
- Initial value: Returns
undefinedon the first render. Type the result asT | undefinedaccordingly. - SSR-safe: Uses only a React ref internally with no browser dependencies.
- See also
useLatestfor accessing the current (most recent) value inside callbacks without stale closures.
Usage
Live Editor
function Demo() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return ( <div> <button onClick={() => setCount(count + 1)}>+</button> <button onClick={() => setCount(count - 1)}>-</button> <p> Now: {count}, before: {prevCount} </p> </div> ); };
Result
API
usePrevious
Returns
T | undefined: previous value
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| state | state value | T (Required) | - |