typescriptbeginner

usePrevious Hook

Track the previous value of any state or prop using a ref-based hook for comparison logic.

typescript
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.