# All files / src useMediaQuery.ts

100% Statements 52/52
100% Branches 11/11
100% Functions 2/2
100% Lines 52/52

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
    45
    46
    47
    48
    49
    50
    51
    52
    531x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    729x
    513x
    105x
    105x
    408x
    408x
    408x
    729x
    729x
    729x
    500x
    100x
    100x
    400x
    400x
    400x
    400x
    400x
    25x
    400x
    400x
    400x
    400x
    400x
    729x
    729x
    729x
    729x
     import { useEffect, useState } from "react";
    import { useSsr } from "./SsrProvider";

    /**
     * @example
     * Simple Example
     * ```tsx
     * import { useMediaQuery } from "@react-md/core";
     * import type { ReactElement } from "react";
     *
     * function Example(): ReactElement {
     *   const matches = useMediaQuery("screen and (min-width: 768px)");
     *
     *   return <>{matches ? "Matches" : "Doesn't"}</>;
     * }
     * ```
     *
     * @param query - The media query to use
     * @param disabled - When `true`, the `window.matchMedia` API will not be
     * activated and the hook will always return `false`.
     * @returns `true` if the media query matches
     * @remarks \@since 6.0.0
     */
    export function useMediaQuery(query: string, disabled = false): boolean {
      const [matches, setMatches] = useState(() => {
        if (typeof window === "undefined" || disabled) {
          return false;
        }

        return window.matchMedia(query).matches;
      });

      const ssr = useSsr();
      useEffect(() => {
        if (disabled || ssr) {
          return;
        }

        const result = window.matchMedia(query);
        setMatches(result.matches);

        const updater = ({ matches }: MediaQueryListEvent): void =>
          setMatches(matches);

        result.addEventListener("change", updater);
        return () => {
          result.removeEventListener("change", updater);
        };
      }, [disabled, query, ssr]);

      return matches;
    }