useIsMobile
True below the md breakpoint (768px).
useIsMobile() is true while the window is narrower than 768px, the width where foundation changes to its phone sizes, and follows the window as it resizes. It is false on the server and on the first render, so the desktop layout is what the HTML carries. Use it when the two layouts are different components, as @khaeli/sidebar does when it becomes a sheet. When only the styling differs, a md: class does the same with no script.
Which layout is active
Window under 768pxNo, desktop layout
"use client"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
export default function UseMobileWhichLayoutIsActive() {
const isMobile = useIsMobile()
return (
<div className="flex w-full max-w-sm flex-col gap-4">
<div className="flex items-center justify-between gap-2">
<span className="text-muted-foreground">Window under 768px</span>
<Badge variant="secondary">{isMobile ? "Yes, phone layout" : "No, desktop layout"}</Badge>
</div>
{/* One row of actions on a desktop, a full-width stack on a phone. */}
<div className={cn("flex gap-2", isMobile ? "flex-col-reverse" : "justify-end")}>
<Button variant="outline" size={isMobile ? "lg" : "default"}>
Save as draft
</Button>
<Button size={isMobile ? "lg" : "default"}>Send invoice</Button>
</div>
</div>
)
}
Installation
npx shadcn@latest add @khaeli/use-mobilebunx --bun shadcn@latest add @khaeli/use-mobileInstalls with
Nothing else. This item needs no other Registry item and no npm package.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/use-mobile.json