Docs
Previous

Previous

Track the previous value of a variable

About

The usePrevious hook tracks the previous value of a variable in a functional component. This is useful for comparing the current value with the previous one, such as triggering actions or rendering based on changes.

Parameters

NameTypeDescription
newValueanyThe new value to track and return the previous of.

Return Values

NameTypeDescription
previousValueanyThe previous value of the provided newValue.

Installation

Run the following command:

npx scriptkavi-hooks@latest add previous

Usage

import { usePrevious } from "@/hooks/previous"
import * as React from "react"
 
function getRandomColor() {
  const colors = ["green", "blue", "purple", "red", "pink"]
  return colors[Math.floor(Math.random() * colors.length)]
}
 
export default function App() {
  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 (
    <section>
      <h1>usePrevious</h1>
      <button className="link" onClick={handleClick}>
        Next
      </button>
      <article>
        <figure>
          <p style={{ background: `var(--${previousColor})` }} />
          <figcaption>Previous: {previousColor}</figcaption>
        </figure>
        <figure>
          <p style={{ background: `var(--${color})` }} />
          <figcaption>Current: {color}</figcaption>
        </figure>
      </article>
    </section>
  )
}