Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

713 B
Raw Blame
import debounce from 'debounce';
import { useEffect, useMemo, useState } from 'react';

interface DebouncedState<T> {
  value: T;
  debounced: T;
  set: React.Dispatch<React.SetStateAction<T>>;
}

export function useDebounceState<T>(
  initialValue: T,
  delay = 500,
  options?: Parameters<typeof debounce>[2]
): DebouncedState<T> {
  const [value, setValue] = useState<T>(initialValue);
  const [debouncedValue, _setDebouncedValue] = useState<T>(initialValue);
  const setDebouncedValue = useMemo(
    () => debounce(_setDebouncedValue, delay, options),
    []
  );
  useEffect(() => {
    setDebouncedValue(value);
  }, [value]);

  return {
    value,
    debounced: debouncedValue,
    set: setValue,
  };
}