# All files / src/media-queries useMediaQuery.ts

100% Statements 53/53
100% Branches 14/14
100% Functions 2/2
100% Lines 53/53

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
    53
    541x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1281x
    1281x
    720x
    12x
    12x
    708x
    708x
    708x
    1281x
    1281x
    711x
    7x
    7x
    704x
    704x
    704x
    704x
    704x
    53x
    704x
    704x
    704x
    704x
    704x
    1281x
    1281x
    1281x
    1281x
     "use client";
    import { useEffect, useState } from "react";
    import { useSsr } from "../SsrProvider.js";

    /**
     * @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 ssr = useSsr();
      const [matches, setMatches] = useState(() => {
        if (typeof window === "undefined" || disabled || ssr) {
          return false;
        }

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

      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;
    }