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

Function useMedia

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

Source from the content-addressed store, hash-verified

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

Callers 5

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

Calls 3

getValueFunction · 0.85
getMediaFunction · 0.85
handlerFunction · 0.70

Tested by

no test coverage detected