🚀   새로운 블로그로 이전했습니다.

(React) useMediaQuery

snippet: react
2023.01.14
1분

Table of contents


React / Next.js 런타임에서 MediaQuery를 충족시켰는지 여부를 알고 싶다.

useMediaQuery.ts
import { useCallback, useEffect, useState } from 'react';

export const useMediaQuery = (width: number) => {
  const [targetReached, setTargetReached] = useState(false);

  const updateTarget = useCallback((e: MediaQueryListEvent) => {
    if (e.matches) setTargetReached(true);
    else setTargetReached(false);
  }, []);

  useEffect(() => {
    const media = window.matchMedia(`(max-width: ${width}px)`);
    media.addEventListener('change', updateTarget);

    if (media.matches) setTargetReached(true);

    return () => media.removeEventListener('change', updateTarget);
  }, []);

  return targetReached;
};

Usage

// 600px
const matches = useMediaQuery(600);

참고 자료