본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

useMediaQuery

원문 보기 위키 갱신

useMediaQuery (미디어 쿼리)

useMediaQuery 훅은 window.matchMedia로 미디어 쿼리를 구독해요. 주어진 미디어 쿼리가 현재 상태와 일치하면 true를 반환해요.

출처: 문서

본문

useMediaQuery 훅은 미디어 쿼리를 구독해요. 인자로 미디어 쿼리를 받아 현재 상태와 일치하면 true를 반환해요. 이 훅은 window.matchMedia() API에 의존하며, API를 사용할 수 없으면 두 번째 인자에 초기 값이 제공되지 않는 한 false를 반환해요.

브라우저 창 크기를 조절하면 window.matchMedia 이벤트가 트리거돼요.

import { Badge } from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';

function Demo() {
  const matches = useMediaQuery('(min-width: 56.25em)');

  return (
    <Badge color={matches ? 'teal' : 'red'}>
      Breakpoint {matches ? 'matches' : 'does not match'}
    </Badge>
  );
}

서버 사이드 렌더링 (Server-Side Rendering)

서버 사이드 렌더링 중에는 window.matchMedia API를 사용할 수 없으므로 훅은 항상 false를 반환해요. 이 동작이 원하는 게 아니라면 초기 값을 재정의할 수 있어요.

import { useMediaQuery } from '@mantine/hooks';

function Demo() {
  // Set the initial value in the second argument and getInitialValueInEffect option to false
  const matches = useMediaQuery('(max-width: 40em)', true, {
    getInitialValueInEffect: false,
  });
}

정의 (Definition)

interface UseMediaQueryOptions {
  getInitialValueInEffect: boolean;
}

function useMediaQuery(
  query: string,
  initialValue?: boolean,
  options?: UseMediaQueryOptions,
): boolean;

Exported types

UseMediaQueryOptions 타입은 @mantine/hooks 패키지에서 내보내져요.

import type { UseMediaQueryOptions } from '@mantine/hooks';

더 알아보기 (Learn more)