Skip to content

usePrevious

React hook to track the previous value of a variable.

Add the hook via the CLI:

sh
npx @novajslabs/cli add usePrevious
sh
npx @novajslabs/cli add usePrevious
sh
pnpm dlx @novajslabs/cli add usePrevious

Or copy and paste the code into your project:

ts
import { useRef } from "react";

export default function usePrevious<T>(value: T): T | undefined {
  const currentRef = useRef<T>(value);
  const previousRef = useRef<T>();

  if (currentRef.current !== value) {
    previousRef.current = currentRef.current;
    currentRef.current = value;
  }

  return previousRef.current;
}
js
import { useRef } from "react";

export default function usePrevious(value) {
  const currentRef = useRef(value);
  const previousRef = useRef();

  if (currentRef.current !== value) {
    previousRef.current = currentRef.current;
    currentRef.current = value;
  }

  return previousRef.current;
}

Requirements

React 16.8 or higher

Parameters

value required

Type: T

The value to track.

Return values

previousValue

Type: T

The previous value of value.

Example

tsx
import { usePrevious } from "./hooks/usePrevious";
import { useState } from "react";

const App = () => {
  const [value, setValue] = useState(0);
  const previousValue = usePrevious(value);

  return (
    <button onClick={() => setValue(value + 1)}>
      Current: {value} - Previous: {previousValue}
    </button>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Track the previous state in a form to validate changes
  • Implement undo functionality in an editor
  • Compare the current and previous prop values in a component
  • Monitor previous API request results for comparison
  • Track previous user inputs in a search bar to optimize suggestions

Released under the MIT License.