shadcn.io is not affiliated with official shadcn/ui
useIsMobile
Reports whether the viewport is below the mobile breakpoint.
Installation
bunx --bun shadcn@latest add https://kit.dev/r/use-is-mobile.jsonpnpm dlx shadcn@latest add https://kit.dev/r/use-is-mobile.jsonnpx shadcn@latest add https://kit.dev/r/use-is-mobile.jsonyarn shadcn@latest add https://kit.dev/r/use-is-mobile.jsonCopy and paste the following code into your project.
import React from "react";
const MOBILE_BREAKPOINT = 768;
export const useIsMobile = () => {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
undefined
);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
};Update the import paths to match your project setup.
Usage
import { useIsMobile } from "@/hooks/use-is-mobile";API Reference
useIsMobile
PropType