usePreviousLoading saved progress…

usePrevious

Build a custom hook that gives a component access to a value from its last render. React always re-renders with the current props and state — but sometimes you need to compare "now" against "a moment ago": did this prop actually change, which direction is a number heading, what was selected before the user picked something new. usePrevious(value) returns whatever value was on the previous render, and undefined on the very first render, when there is no previous yet.

Signature

function usePrevious<T>(value: T): T | undefined;

The returned value lags exactly one render behind the input. It is undefined only on the first render.

Examples

function Price({ amount }) {
  const previous = usePrevious(amount);
  const direction =
    previous === undefined ? 'first' : amount > previous ? 'up' : 'down';

  return <span data-trend={direction}>{amount}</span>;
}
// render 1: amount=100 → previous=undefined → 'first'
// render 2: amount=120 → previous=100       → 'up'
// render 3: amount=90  → previous=120       → 'down'
// The hook lags one render behind the value it is given:
// value:   1          2     3     4
// returns: undefined  1     2     3

Notes

  • First render returns undefined. There is no earlier render to remember, so the very first call yields undefined.
  • It lags exactly one render. After a render with value X, the next render's usePrevious returns X — never two renders back.
  • Falsy values are real values. If the previous value was 0, '', or false, the hook must return that, not undefined. "No previous value" and "a previous value that happens to be falsy" are different.
  • Identity is preserved. For objects and arrays, return the same reference that was passed last render, not a copy.
Loading editor…