2023-09-09 03:39:10 +08:00
|
|
|
/*
|
2024-09-06 16:22:13 +08:00
|
|
|
Copyright 2023, 2024 New Vector Ltd.
|
2023-09-09 03:39:10 +08:00
|
|
|
|
2024-09-06 16:22:13 +08:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
Please see LICENSE in the repository root for full details.
|
2023-09-09 03:39:10 +08:00
|
|
|
*/
|
|
|
|
|
|
|
|
import { useCallback, useMemo, useState } from "react";
|
|
|
|
|
|
|
|
import { useEventTarget } from "./useEvents";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* React hook that tracks whether the given media query matches.
|
|
|
|
*/
|
2023-09-23 06:05:13 +08:00
|
|
|
export function useMediaQuery(query: string): boolean {
|
2023-09-09 03:39:10 +08:00
|
|
|
const mediaQuery = useMemo(() => matchMedia(query), [query]);
|
|
|
|
|
|
|
|
const [numChanges, setNumChanges] = useState(0);
|
|
|
|
useEventTarget(
|
|
|
|
mediaQuery,
|
|
|
|
"change",
|
2023-10-11 22:42:04 +08:00
|
|
|
useCallback(() => setNumChanges((n) => n + 1), [setNumChanges]),
|
2023-09-09 03:39:10 +08:00
|
|
|
);
|
|
|
|
|
|
|
|
// We want any change to the update counter to trigger an update here
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
return useMemo(() => mediaQuery.matches, [mediaQuery, numChanges]);
|
2023-09-23 06:05:13 +08:00
|
|
|
}
|