All hooks / Component helpers
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
import { usePrevious } from '@vincent.ri/react-tils'
// or only this hook
import { usePrevious } from '@vincent.ri/react-tils/usePrevious'Usage
const previous = usePrevious(price)
const trend = previous === undefined ? '' : price > previous ? '▲' : price < previous ? '▼' : ''
return <span>{price} {trend}</span>Live demo
Change the price; an unrelated re-render keeps the previous one.
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
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
Uses only long-established browser features, so it works wherever React does.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).