usePrevious

Mar 17, 2024

Save the previous state of a value.

export function usePrevious<T>(value: T, initial: T): T {
  const ref = useRef<T>(initial)

  useEffect(() => {
    ref.current = value
  }, [value])

  return ref.current
}