All files / src/useStates useDeepState.ts

100% Statements 3/3
100% Branches 6/6
100% Functions 2/2
100% Lines 3/3

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                            26x 26x 12x              
import isEqual from "lodash/isEqual";
import { Dispatch, useReducer } from "react";
 
/**
 * This is similar to the `React.useState` function except it uses
 * [lodash.isEqual](https://lodash.com/docs/4.17.15#isEqual) to perform a
 * deep comparison of the values.
 * @param initialState - initial state
 * @returns state, setter
 *
 */
export function useDeepState<S>(
  initialState?: S | (() => S)
): [S, Dispatch<S>] {
  const initialStateIsFunction = typeof initialState === "function";
  return useReducer(
    (state: S, newState: S) => (isEqual(state, newState) ? state : newState),
    initialStateIsFunction ? (null as unknown as S) : initialState,
    initialStateIsFunction
      ? (initialState as () => S)
      : (undefined as unknown as () => S)
  );
}