mirror of
https://github.com/tinyhumansai/openhuman.git
synced 2026-07-30 23:14:37 +00:00
28 lines
880 B
TypeScript
28 lines
880 B
TypeScript
import { useSyncExternalStore } from 'react';
|
|
|
|
/**
|
|
* Subscribes to a CSS media query and returns whether it currently matches.
|
|
* SSR/test-safe: returns false when matchMedia is unavailable.
|
|
*/
|
|
export const useMediaQuery = (query: string): boolean => {
|
|
const subscribe = (onStoreChange: () => void) => {
|
|
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
|
|
return () => {};
|
|
}
|
|
const mql = window.matchMedia(query);
|
|
mql.addEventListener('change', onStoreChange);
|
|
return () => mql.removeEventListener('change', onStoreChange);
|
|
};
|
|
|
|
const getSnapshot = () => {
|
|
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
|
|
return false;
|
|
}
|
|
return window.matchMedia(query).matches;
|
|
};
|
|
|
|
return useSyncExternalStore(subscribe, getSnapshot, () => false);
|
|
};
|
|
|
|
export default useMediaQuery;
|