MCPcopy Create free account
hub / github.com/dailydotdev/apps / useMedia

Function useMedia

packages/shared/src/hooks/useMedia.ts:14–63  ·  view source on GitHub ↗
(
  queries: string[],
  values: T[],
  defaultValue: T,
  ssrValue = defaultValue,
  afterHydration = false,
)

Source from the content-addressed store, hash-verified

12let hydrated = false;
13
14export default function useMedia<T>(
15 queries: string[],
16 values: T[],
17 defaultValue: T,
18 ssrValue = defaultValue,
19 afterHydration = false,
20): T {
21 const getMedia = (): MediaQueryList[] =>
22 queries.map((q) => window.matchMedia(q));
23
24 const getValue = (mediaQueryLists: MediaQueryList[]) => {
25 const index = mediaQueryLists.findIndex((mql) => mql.matches);
26 return values?.[index] || defaultValue;
27 };
28
29 const [value, setValue] = useState<T>(() => {
30 if (afterHydration && !hydrated) {
31 return undefined as T;
32 }
33
34 return typeof window !== 'undefined' ? getValue(getMedia()) : ssrValue;
35 });
36
37 useEffect(() => {
38 hydrated = true;
39 const mediaQueryLists = getMedia();
40 const handler = () => setValue(getValue(mediaQueryLists));
41 handler();
42 const isModern = 'addEventListener' in mediaQueryLists[0];
43 mediaQueryLists.forEach((mql) => {
44 if (isModern) {
45 mql.addEventListener('change', handler);
46 } else {
47 mql.addListener(handler);
48 }
49 });
50 return () =>
51 mediaQueryLists.forEach((mql) => {
52 if (isModern) {
53 mql.removeEventListener('change', handler);
54 } else {
55 mql.removeListener(handler);
56 }
57 });
58 // @NOTE see https://dailydotdev.atlassian.net/l/cp/dK9h1zoM
59 // eslint-disable-next-line react-hooks/exhaustive-deps
60 }, [values, queries]);
61
62 return value;
63}
64
65export const useMediaClient = <T>(
66 queries: string[],

Callers 6

useReadPostButtonTextFunction · 0.90
FeedLayoutProviderFunction · 0.90
useViewSizeFunction · 0.90
useMediaClientFunction · 0.85

Calls 3

getMediaFunction · 0.85
getValueFunction · 0.70
handlerFunction · 0.70

Tested by

no test coverage detected