Rooks
HooksState Management

usePreviousDifferent

Returns the most recent previous value that was different from the current one.

About

usePreviousDifferent remembers the most recent committed value that is not strictly equal (===) to the current value. It is useful when repeated equal renders should not replace the comparison value.

Examples

import { usePreviousDifferent, useCounter } from "rooks";

function App() {
  const { value: counter1Value, increment: incrementCounter1 } = useCounter(0);
  const previousCounter1Value = usePreviousDifferent(counter1Value);
  const { value: counter2Value, increment: incrementCounter2 } = useCounter(0);
  const previousCounter2Value = usePreviousDifferent(counter2Value);
  return (
    <div
      style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
    >
      <h2>Previous different values</h2>
      <p>
        Notice how previously different values are tracked across rerenders and
        when other values change.
      </p>
      <div>
        <p>Counter: {String(counter1Value)}</p>
        <p>Previous Counter 1 value: {String(previousCounter1Value)}</p>
        <p>Counter: {String(counter2Value)}</p>
        <p>Previous Counter 1 value: {String(previousCounter2Value)}</p>
        <button onClick={incrementCounter1}>Increment counter 1</button>
        <br />
        <button onClick={incrementCounter2}>Increment counter 2</button>
      </div>
    </div>
  );
}

export default App;

Parameters

ParameterTypeDefaultDescription
currentValueTRequiredValue whose history is tracked.

Return value

Returns T | null. It is null before a different committed value exists.

Behavior and lifecycle

History refs update after commit in an effect keyed by currentValue. During render, the hook compares with strict equality and returns the last committed different value. Object values are compared by reference, not deeply. The history is local to the component and is discarded on unmount.

Compatibility and accessibility

The hook is SSR-safe and uses no browser APIs. If the previous value is shown to users, label it clearly so it is not confused with the current value.

On this page