UNPKG

@jk-core/hooks

Version:
59 lines (48 loc) 1.48 kB
import { useEffect, useRef, useState } from 'react'; const useMediaQuery = (width: number) => { const isWindowDefined = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const [matches, setMatches] = useState(() => { if (!isWindowDefined) { return false; } try { return window.matchMedia(`(max-width: ${width}px)`).matches; } catch { return false; } }); const matchMediaRef = useRef<MediaQueryList | null>(null); useEffect(() => { if (!isWindowDefined) { return; } try { const matchMedia = window.matchMedia(`(max-width: ${width}px)`); matchMediaRef.current = matchMedia; const handleChange = () => { try { setMatches(window.matchMedia(`(max-width: ${width}px)`).matches); } catch { // 조용히 실패 처리 } }; // 최신 브라우저는 addEventListener를 지원 if (matchMedia.addEventListener) { matchMedia.addEventListener('change', handleChange); return () => { matchMedia.removeEventListener('change', handleChange); }; } // 구형 브라우저 호환성 (addListener/removeListener) matchMedia.addListener(handleChange); return () => { matchMedia.removeListener(handleChange); }; } catch { // 조용히 실패 처리 } }, [isWindowDefined, width]); return matches; }; export default useMediaQuery;