Dakik// Bits
Dakik.co.uk
All bits

// Utilities

useIsMobile

Hook that tracks whether the viewport is below the mobile breakpoint.

// Rendering preview…

// Install

npx shadcn@latest add @dakik/use-is-mobile

// Usage

1import { useIsMobile } from "@/hooks/use-is-mobile";

// Code

1import React from "react";
2
3const MOBILE_BREAKPOINT = 768;
4
5export const useIsMobile = () => {
6 const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
7 undefined
8 );
9
10 React.useEffect(() => {
11 const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
12
13 const onChange = () => {
14 setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
15 };
16
17 mql.addEventListener("change", onChange);
18
19 setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
20
21 return () => mql.removeEventListener("change", onChange);
22 }, []);
23
24 return !!isMobile;
25};
26