KooKs

useIsMobile

접속 환경이 모바일인지 확인하는 커스텀 훅
ReactTypescript

예시

현재 접속 환경
User Agent 기반 모바일 여부: 데스크톱
화면 너비 기반 모바일 여부: 데스크톱
브라우저 창의 크기를 조절하여 결과를 확인해보세요!

API

useIsMobile()
  • Parameters
    • props (Object)Hook의 설정값
    • props.width (number)모바일 환경을 판단할 기준 너비 (px). 기본값: 768
  • Returns
    • isMobile (boolean)User Agent 기반 모바일 여부
    • isMobileByWidth (boolean)화면 너비 기반 모바일 여부

개발 및 사용환경

ReactTypescript

Usage

1import { useIsMobile } from "@kooks-fe/kooks/react";
2
3function MyComponent() {
4  const { isMobile, isMobileByWidth } = useIsMobile();
5
6  return (
7    <div>
8      {isMobile ? (
9        <MobileLayout />
10      ) : (
11        <DesktopLayout />
12      )}
13    </div>
14  );
15}

Hook

1import { useEffect, useState } from "react";
2
3interface UseIsMobileResult {
4  isMobile: boolean;
5  isMobileByWidth: boolean;
6}
7
8/**
9 * 사용자의 접속 환경이 모바일인지 확인하는 Hook
10 *
11 * 이 훅은 두 가지 방법으로 모바일 환경을 판단합니다:
12 * 1. User Agent 문자열을 분석하여 모바일 기기 여부 확인
13 * 2. 화면 너비를 기준으로 모바일 환경 여부 판단 (기본값: 768px)
14 *
15 * @param {number} [width=768] - 모바일 환경을 판단할 기준 너비 (px)
16 * @returns {Object} 모바일 환경 여부를 나타내는 객체
17 *   - isMobile: User Agent 기반 모바일 여부
18 *   - isMobileByWidth: 화면 너비 기반 모바일 여부
19 */
20export function useIsMobile(width: number = 768): UseIsMobileResult {
21  const [isMobile, setIsMobile] = useState(false);
22  const [isMobileByWidth, setIsMobileByWidth] = useState(false);
23
24  useEffect(() => {
25    const checkUserAgent = () => {
26      if (typeof navigator === "undefined") return false;
27      const userAgent = navigator.userAgent;
28      const mobileRegex =
29        /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
30      return mobileRegex.test(userAgent);
31    };
32
33    const checkWidth = () => {
34      if (typeof window === "undefined") return false;
35      return window.innerWidth <= width;
36    };
37
38    const updateStates = () => {
39      setIsMobile(checkUserAgent());
40      setIsMobileByWidth(checkWidth());
41    };
42
43    updateStates(); // 최초 실행
44  }, []);
45
46  return { isMobile, isMobileByWidth };
47}