All files / src/useStates useDebouncedState.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 25 26                                        4x 4x 4x 4x    
import debounce from "lodash/debounce";
import { Dispatch, useEffect, useState } from "react";
 
/**
 * This is a variant of set state that debounces rapid changes to a state.
 * This performs a shallow state check, use {@link useDebouncedDeepState}
 * for a deep comparison.  Internally this uses
 * [lodash debounce](https://lodash.com/docs/#debounce) to perform
 * the debounce operation.
 * @param initialValue - initial value
 * @param waitMillis - The number of milliseconds to delay.
 * @param debounceSettings - debounce settings.
 * @returns state and setter
 *
 */
export function useDebouncedState<S>(
  initialValue: S,
  waitMillis: number,
  debounceSettings?: Parameters<typeof debounce>[2]
): [S, Dispatch<S>] {
  const [state, setState] = useState<S>(initialValue);
  const debouncedSetState = debounce(setState, waitMillis, debounceSettings);
  useEffect(() => () => debouncedSetState.cancel(), [debouncedSetState]);
  return [state, debouncedSetState];
}