TypeScript

usePrevious — Track Last Render's Value

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Returns the value the prop/state had on the previous render. Useful for detecting transitions (e.g. "the count just went from 0 to 1") inside effects.
TypeScript
Raw
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;
}

// Detect transitions:
function Counter({ count }: { count: number }) {
  const prev = usePrevious(count);
  useEffect(() => {
    if (prev !== undefined && prev !== count) {
      console.log(`changed: ${prev} → ${count}`);
    }
  }, [count, prev]);
  return <span>{count}</span>;
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.