Store the previous render’s value.
Section: Common UI Hooks
Track previous value
tsx
tsx
function usePrevious<T>(value: T) {
const ref = useRef<T | undefined>(undefined);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}Explanation
Useful for comparisons, transitions, analytics, and animation decisions.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Common UI Hooks
Handle clicks outside an element
Close menus or popovers when a click happens outside a ref.
Custom hook with options object
Prefer options objects for extensible APIs.