All files / src/useStates useSignal.ts

0% Statements 0/7
0% Branches 0/3
0% Functions 0/3
0% Lines 0/7

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 27 28                                                       
import noop from "lodash/noop";
import { Dispatch, useState } from "react";
 
/**
 * This is like `useState<boolean>` but provides explicit methods to set the value.  This either sets it to
 * true or the initial state.  If the intial state is true then this will always be true.
 * @returns an array containing the signal value, a setter callback and a reset back to initial value callback
 */
export const useSignal = (
  initial: boolean = false,
  signalCallback: Dispatch<boolean> = noop,
  resetCallback: Dispatch<boolean> = noop
): [boolean, () => void, () => void] => {
  const [signal, setSignal] = useState(initial);
 
  return [
    signal,
    () => {
      signalCallback(signal);
      setSignal(true);
    },
    () => {
      resetCallback(signal);
      setSignal(initial);
    },
  ];
};