All files / src/useMounted useMounted.ts

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

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                    11x 11x 6x 6x 6x     11x    
import { useCallback, useEffect, useRef } from "react";
 
import type { IsMountedFunction } from "./IsMountedFunction";
/**
 * This hook provides a function that returns whether the component is still mounted.
 * This is useful as a check before calling set state operations which will generates
 * a warning when it is called when the component is unmounted.
 * @returns a function that returns true if the component is still mounted.
 */
export function useMounted(): IsMountedFunction {
  const mountedRef = useRef(false);
  useEffect(() => {
    mountedRef.current = true;
    return function useMountedEffectCleanup() {
      mountedRef.current = false;
    };
  }, []);
  return useCallback(() => mountedRef.current, [mountedRef]);
}