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
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
newValue | T | The new value to track and return the previous value of. | - | No |
initialPreviousValue | T | null | The initial value to use as the previous value before the first update. Defaults to null . | null | Yes |
Return Values
Name | Type | Description |
---|---|---|
previousValue | T | null | undefined | The previous value of the provided newValue . Initially, this will be initialPreviousValue or null . |