All files / src/useStates useStateIfMounted.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 4/4
100% Lines 9/9

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 29 30 31 32                                6x 6x 3x 3x 3x     6x   6x 3x     6x    
import { Dispatch, useEffect, useRef, useState } from "react";
 
/**
 * This is a version of useState that will detect if the component is
 * still mounted.  This hides the warning that would normally appear
 * if set state is called when the component is unmounted so it
 * is advised *NOT* to use this unless there's a specific reason
 * such as a an Axios interceptor that may be used to change state
 * when it is unable to refresh an auth token.
 * @param initialState - initisl state
 * @returns state, setter
 *
 */
export function useStateIfMounted<S>(
  initialState: S | (() => S)
): [S, Dispatch<S>] {
  const mountedRef = useRef(false);
  useEffect(() => {
    mountedRef.current = true;
    return function useMountedEffectCleanup() {
      mountedRef.current = false;
    };
  }, []);
  const [state, setState] = useState(initialState);
  function setStateIfMounted(next: S) {
    if (mountedRef.current) {
      setState(next);
    }
  }
  return [state, setStateIfMounted];
}