Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

use-media-query.ts

17 lines468 Bytes

1import { useCallback, useSyncExternalStore } from "react";
2​
3export function useMediaQuery(query: string): boolean {
4 const subscribe = useCallback(
5 (onChange: () => void) => {
6 const media = matchMedia(query);
7 media.addEventListener("change", onChange);
8 return () => media.removeEventListener("change", onChange);
9 },
10 [query],
11 );
12 return useSyncExternalStore(
13 subscribe,
14 () => matchMedia(query).matches,
15 () => false,
16 );