usePreviousstate

usePrevious

NewSSR SAFE

Stores previous value of a state or prop across renders.

$ pnpm dlx shadcn@latest add @byphongphan/use-previous
Requires @byphongphan in components.json
state
Loading preview...

Installation

$ pnpm dlx shadcn@latest add @byphongphan/use-previous
Requires @byphongphan in components.json

Usage

import { useState } from "react"import { usePrevious } from "@/shared/hooks"
export function Counter() { const [count, setCount] = useState(0) const previousCount = usePrevious(count)
return ( <div> <p>Current: {count}</p> <p>Previous: {previousCount ?? "None"}</p> <button onClick={() => setCount((c) => c + 1)}>Increment</button> </div> )}

Props & Parameters

ParamTypeDefaultDescription
valueT—Any state or prop value to track across render cycles.

Returns

ReturnTypeDescription
previousValueT | undefinedThe value from the previous render cycle, or undefined on the initial mount.

Command Palette

Quick search and commands navigation