Skip to content

usePrevious

Tracks the changes of a given state and returns always its previous value.

Installation

npx rabbithook@latest add use-previous

Usage

App.tsx
import usePrevious from "@/hooks/use-previous";
function Component() {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);
return (
<>
<p>Count: { count }</p> {/* 0, 1, 2, 3, ... */}
<p>Previous Count: { previousCount }</p> {/* undefined, 0, 1, 2, ... */}
<button onClick={() => setCount(prev => prev++)}>
Increment
</button>
</>
);
}

Code

use-previous.ts
import { useRef } from "react";
function usePrevious<T>(value: T): T | undefined {
const currentRef = useRef<T>(value);
const previousRef = useRef<T>();
if (currentRef.current !== value) {
previousRef.current = currentRef.current;
currentRef.current = value;
}
return previousRef.current;
}
export default usePrevious;