usePrevious & useIsFirstRender in React

From the React Custom Hooks cheat sheet · Interaction & Lifecycle Hooks · verified Jul 2026

usePrevious & useIsFirstRender

Track the previous value of a variable, detect the first render

jsx
import { useRef, useEffect } from 'react'

function usePrevious<T>(value: T): T | undefined {
  const ref = useRef<T | undefined>(undefined)
  useEffect(() => { ref.current = value }, [value])
  return ref.current
}

// Usage
function Counter({ count }: { count: number }) {
  const prev = usePrevious(count)
  return <p>Now: {count}, was: {prev ?? '-'}</p>
}
💡 usePrevious is two lines: a ref + effect - no library needed
📌 useUpdateEffect skips the mount run - perfect for "fire on change" UX
⚡ useIsFirstRender returns true exactly once per component lifetime
🎯 Combine usePrevious + a CSS class for cheap value-change flash effects
lifecyclepatterns

More React tasks

Back to the full React Custom Hooks cheat sheet