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 const usePrevious = <T>(value: T): T | undefined => {
  const currentRef = useRef<T>(value);
  const previousRef = useRef<T>(undefined);

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

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

export const usePrevious = (value) => {
  const currentRef = useRef(value);
  const previousRef = useRef(undefined);

  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.

Examples of common use cases