shadcn.io is not affiliated with official shadcn/ui
useIsMobile
Reports whether the viewport is below the mobile breakpoint.
useIsMobile tells you if the viewport is less than 768px. It uses matchMedia, so it reacts instantly to browser zoom and device rotation, not just window resizing.
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.jsonThis hook has no package dependencies beyond React.
Copy 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 "@/registry/react/hooks/use-is-mobile";Example
"use client";
import { useIsMobile } from "@/registry/react/hooks/use-is-mobile";
export function Example() {
const isMobile = useIsMobile();
return (
<p className="text-muted-foreground text-sm">
{isMobile ? "Mobile layout" : "Desktop layout"}
</p>
);
}