usePrevious
EditReads the value from the preceding committed render.
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;}Download
Section titled “Download”wget -O src/hooks/usePrevious.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/react-hooks/usePrevious.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/react-hooks "$temp_dir" && mv "$temp_dir/usePrevious.ts" src/hooks/usePrevious.ts && rm -r "$temp_dir"Examples
Section titled “Examples”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.
Returns
Section titled “Returns”Without an initial value, Value | undefined. Supplying initialValue returns
Value | Initial.