Docs
usePrevious

Track the previous value of a variable with usePrevious.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-previous

Usage

"use client"
 
import * as React from "react"
 
import { usePrevious } from "@/hooks/use-previous"
 
export function Component() {
  const [count, setCount] = React.useState(0)
  const previousCount = usePrevious(count, -1) // Initial previous value is -1
 
  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {previousCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
newValueTThe new value to track and return the previous value of.-No
initialPreviousValueT | nullThe initial value to use as the previous value before the first update. Defaults to null.nullYes

Return Values

NameTypeDescription
previousValueT | null | undefinedThe previous value of the provided newValue. Initially, this will be initialPreviousValue or null.