mwui
GitHub

usePrevious

A hook that remembers the value from before the most recent change.

Previous

Current

12

Direction

Re-rendering without changing the value leaves the previous value untouched.

Installation

Usage

Useful whenever a render needs to know where a value came from: animating a number in the direction it moved, highlighting a row that just changed, or firing a transition only on the edge.

import { usePrevious } from "@/hooks/use-previous";

function Score({ value }: { value: number }) {
  const previous = usePrevious(value);
  const direction = previous === undefined ? "flat" : value > previous ? "up" : "down";

  return <span data-direction={direction}>{value}</span>;
}

The value it actually returns

The common useRef + useEffect implementation returns "the value at the last commit", which quietly becomes the current value as soon as the component re-renders for an unrelated reason — a parent update, a sibling state change. That makes it unreliable exactly when you compare against it in render.

This version stores the previous value in state and updates it during render, the pattern React documents for deriving state from props. It returns the value from before the last change, and holds that value steady across re-renders that did not change the input.

const previous = usePrevious(value);
// value: 1 → 1 → 2 → 2 → 2
// previous: undefined → undefined → 1 → 1 → 1

undefined on the first render means there is no previous value yet — not that the previous value was undefined.

Comparison

Objects and arrays rebuilt each render would register as a change under the default Object.is. Pass a comparator:

const previousRange = usePrevious(range, (a, b) => a.start === b.start && a.end === b.end);