usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
import { useEffect, useRef } from 'react';
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
// Usage:
// const [count, setCount] = useState(0);
// const prevCount = usePrevious(count);
// console.log(`Changed from ${prevCount} to ${count}`);Use Cases
- Detecting value changes
- Animation transitions
- Undo functionality
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.