useDebouncedState.tsx 752 B

12345678910111213141516171819202122
  1. import {useCallback, useState} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import type {DebouncedFunc} from 'lodash';
  4. import debounce from 'lodash/debounce';
  5. // NOTE: This can be extracted for more general use if:
  6. // 1. It gets some thorough tests
  7. // 2. It correctly cancels debounces
  8. export function useDebouncedState<T>(
  9. initialValue: T,
  10. deps: React.DependencyList,
  11. delay: number = DEFAULT_DEBOUNCE
  12. ): [T, DebouncedFunc<React.Dispatch<React.SetStateAction<T>>>] {
  13. const [value, setValue] = useState<T>(initialValue);
  14. // eslint-disable-next-line react-hooks/exhaustive-deps
  15. const debouncedSetValue = useCallback(debounce(setValue, delay), deps);
  16. return [value, debouncedSetValue];
  17. }
  18. const DEFAULT_DEBOUNCE = 100;