# All files / src useUnmounted.ts

100% Statements 44/44
100% Branches 3/3
100% Functions 1/1
100% Lines 44/44

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
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    451x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    33x
    33x
    11x
    11x
    11x
    11x
    33x
    33x
    33x
    33x
     "use client";
    import { useEffect, useRef } from "react";
    import type { NonNullRef } from "./types.js";

    /**
     * @example
     * Simple Example
     * ```tsx
     * import { useUnmounted } from "@react-md/core";
     * import { useEffect, useState } from "react";
     *
     * function Example(): ReactElement {
     *   const [state, setState] = useState({ loading: false });
     *   const unmounted = useUnmounted();
     *
     *   useEffect(() => {
     *     async function load(): void {
     *       const result = await fetch('/some-api');
     *       const json = await response.json();
     *       if (!unmounted.current) {
     *         setState({ loading: false, result: json });
     *       }
     *     }
     *
     *     setState({ loading: true });
     *     load();
     *   }, [unmounted]);
     *
     *   return null;
     * }
     * ```
     * @remarks \@since 6.0.0
     */
    export function useUnmounted(): NonNullRef<boolean> {
      const unmounted = useRef(false);
      useEffect(() => {
        unmounted.current = false;
        return () => {
          unmounted.current = true;
        };
      }, []);

      return unmounted;
    }