dotUI
dotUI
beta
  1. Hooks
  2. Browser hooks
  3. usePrevious

usePrevious

Track the previous value of a variable with usePrevious.

"use client";

import React from "react";
import { Button } from "@/lib/components/core/default/button";
import { usePrevious } from "@/lib/hooks/use-previous";

function getRandomColor() {
  const colors = ["green", "blue", "purple", "red", "pink"];
  return colors[Math.floor(Math.random() * colors.length)];
}

function Demo() {
  const [color, setColor] = React.useState(getRandomColor());
  const previousColor = usePrevious(color);

  const handleClick = () => {
    function getNewColor() {
      const newColor = getRandomColor();
      if (color === newColor) {
        getNewColor();
      } else {
        setColor(newColor);
      }
    }
    getNewColor();
  };

  return (
    <div className="text-center">
      <Button size="sm" onPress={handleClick}>
        Next
      </Button>
      <div className="mt-8 grid grid-cols-2 gap-4">
        <div
          className="flex h-16 w-52 items-center justify-center rounded-lg"
          style={{ background: previousColor ?? undefined }}
        >
          Previous: {previousColor ?? "null"}
        </div>
        <div
          className="flex h-16 w-52 items-center justify-center rounded-lg"
          style={{ background: color }}
        >
          Previous: {color ?? "null"}
        </div>
      </div>
    </div>
  );
}

Installation

Copy and paste the following code into your project.

import React from "react";

export function usePrevious<T>(value: T) {
  const [current, setCurrent] = React.useState(value);
  const [previous, setPrevious] = React.useState<T | null>(null);

  if (value !== current) {
    setPrevious(current);
    setCurrent(value);
  }

  return previous;
}

Update the import paths to match your project setup.

Parameters

NameTypeDescription
newValue
any
The new value to track and return the previous of.

Return value

NameTypeDescription
previousValue
any
The previous value of the provided newValue.

Built by mehdibha. The source code is available on GitHub.