@technobuddha > react-hooks > React > Hooks
Function: usePrevious()
ts
function usePrevious<T>(value: T | (prevValue: undefined | T) => T): undefined | T;Defined in: use-previous.ts:30
Tracks the previous value of a variable across renders.
On the first render, returns undefined. On subsequent renders, returns the value from the previous render. If you pass a function, it will be called with the previous value to compute the new value.
Useful for comparing previous and current values, animations, or debugging.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | (prevValue: undefined | T) => T | The current value, or a function that receives the previous value and returns the new value. |
Returns
undefined | T
The previous value.
Example
typescript
function Example({ count }: { count: number }) {
const prevCount = usePrevious(count);
return (
<div>
<div>Current: {'{'}count{'}'}</div>
<div>Previous: {'{'}prevCount{'}'}</div>
</div>
);
}