usePrevious

Stores and returns the previous value of a given state or prop.

Code

1import { useRef, useEffect } from "react"
2
3export function usePrevious<T>(value: T): T | undefined {
4  const ref = useRef<T>()
5
6  useEffect(() => {
7    ref.current = value
8  }, [value])
9
10  return ref.current
11}

Usage Example

import { useState } from "react" import { usePrevious } from "@/hooks/use-previous" import { Button } from "@/components/ui/button" export function PreviousExample() { const [count, setCount] = useState(0) const prevCount = usePrevious(count) return ( <div className="space-y-4"> <p className="text-lg">Current Count: {count}</p> <p className="text-lg text-npui-muted-foreground">Previous Count: {prevCount ?? 'N/A'}</p> <Button onClick={() => setCount(count + 1)}>Increment</Button> </div> ) }