The Hook
React doesn't provide a usePrevious hook out of the box, but it's easy to write.
import { useRef, useEffect } from 'react';
function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]); // Update ref AFTER render
return ref.current; // Return value BEFORE update
}
Usage
function Counter() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<h1>
Now: {count}, Before: {prevCount}
</h1>
);
}
Sponsored Content
Google AdSense Placeholder
CONTENT SLOT