Skip to content

usePrevious

Edit

Reads the value from the preceding committed render.

usePrevious.ts
import { useEffect, useRef } from "react";
export function usePrevious<Value>(value: Value): Value | undefined;
export function usePrevious<Value, Initial>(
value: Value,
initialValue: Initial,
): Value | Initial;
export function usePrevious<Value, Initial>(
value: Value,
initialValue?: Initial,
): Value | Initial | undefined {
const previousRef = useRef<Value | Initial | undefined>(initialValue);
useEffect(() => {
previousRef.current = value;
}, [value]);
return previousRef.current;
}
Terminal
wget -O src/hooks/usePrevious.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/react-hooks/usePrevious.ts
usePrevious.example.tsx
import { useState } from "react";
import { usePrevious } from "./usePrevious";
export function PreviousExample() {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);
return (
<div>
<p>Current: {count}</p>
<p>Previous: {previousCount ?? "none"}</p>
<button type="button" onClick={() => setCount((value) => value + 1)}>
Increment
</button>
</div>
);
}
  • value (Value) — Value to remember after the current render commits.
  • initialValue (Initial, optional) — Value returned before the first update.

Without an initial value, Value | undefined. Supplying initialValue returns Value | Initial.