All files / src/useStates useDebouncedDeepState.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 3/3
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                                    8x 8x 8x 8x    
import debounce from "lodash/debounce";
import { Dispatch, useEffect } from "react";
 
import { useDeepState } from "./useDeepState";
 
/**
 *
 * @param initialValue - initial value
 * @param waitMillis - The number of milliseconds to delay.
 * @param debounceSettings - settings passed to the debounce function
 * @returns state, setter
 *
 */
export function useDebouncedDeepState<S>(
  initialValue: S,
  waitMillis: number,
  debounceSettings?: Parameters<typeof debounce>[2]
): [S, Dispatch<S>] {
  const [state, setState] = useDeepState<S>(initialValue);
  const debouncedSetState = debounce(setState, waitMillis, debounceSettings);
  useEffect(() => () => debouncedSetState.cancel(), [debouncedSetState]);
  return [state, debouncedSetState];
}