# usePrevious

The value `value` had before it last changed, or `undefined` until it first changes. Re-renders that don't change `value` keep the same previous value, so it answers "what was it before?", not "what was it last render?".

Kept in state, not read from a ref during render, so it's correct under the React Compiler, Strict Mode, and concurrent rendering, where the common ref version (`useRef` + `useEffect`) shows stale or skipped values. Compares with `Object.is`, like React: a new object or array each render counts as a change, so pass a primitive or a memoized value.

## Import

```ts
import { usePrevious } from '@vincent.ri/react-tils'
// or only this hook
import { usePrevious } from '@vincent.ri/react-tils/usePrevious'
```

## Usage

```ts
const previous = usePrevious(price)
const trend = previous === undefined ? '' : price > previous ? '▲' : price < previous ? '▼' : ''
return <span>{price} {trend}</span>
```

## When to use it

Rendering from the change itself: a direction (price up or down, slide left or right), "changed from X to Y", or animating from the old value.

## When not to

You want to run code when a value changes; do it in the event handler that changes it, or in an effect with that value as a dependency. For a prop to state copy, see `useControllableState`.

## API

```ts
function usePrevious<T>(value: T): T | undefined
```

| Parameter | Description |
| --- | --- |
| `value` | The value to follow. |

**Returns** The value before the latest change, or `undefined` before any change.

## Browser support

Works in all modern browsers.

---

92 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/usePrevious.ts
Docs page: https://vincentri.github.io/react-tils/hooks/usePrevious/
Previous: [useAnnounce](https://vincentri.github.io/react-tils/hooks/useAnnounce.md)
