Skip to content

Commit

Permalink
feat: useMediaQueries hook 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
feb-dain committed Sep 1, 2023
1 parent 7daf1e8 commit 0e1fcef
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions frontend/src/hooks/useMediaQueries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { useEffect, useMemo, useState } from 'react';

import { MOBILE_BREAKPOINT } from '@constants';

type ScreenBreakpoint = 'mobile';

type ScreenKey = `is${Capitalize<ScreenBreakpoint>}`;
type Screen = Map<ScreenKey, MediaQueryList>;

/**
* @example screen.get('isMobile') ? '100%' : '32rem';
*/
const useMediaQueries = () => {
const mediaQueries = useMemo<Screen>(() => {
return new Map([['isMobile', window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT}px)`)]]);
}, []);

const [screen, setScreen] = useState(
new Map([...mediaQueries].map(([key, mediaQuery]) => [key, mediaQuery.matches]))
);

useEffect(() => {
const cleanHandlers = [...mediaQueries].map(([key, mediaQuery]) => {
const handleMediaQueryChange = ({ matches }: MediaQueryListEvent) => {
setScreen((screen) => new Map(screen).set(key, matches));
};

mediaQuery.addEventListener('change', handleMediaQueryChange);

return () => mediaQuery.removeEventListener('change', handleMediaQueryChange);
});

return () => cleanHandlers.forEach((cleanHandler) => cleanHandler());
}, []);

return screen;
};

export default useMediaQueries;

0 comments on commit 0e1fcef

Please sign in to comment.