# Use Mobile

A hook that tracks whether the viewport is mobile-sized.

## Installation

```bash
npx shadcn@latest add https://landorui.landorestate.com/r/use-mobile.json
```

[Registry JSON](https://landorui.landorestate.com/r/use-mobile.json)

## Preview

```tsx
import { useIsMobile } from "@/hooks/use-mobile";

export function Preview() {
  const isMobile = useIsMobile();

  return <p className="text-sm">The viewport is currently {isMobile ? "mobile" : "desktop"}.</p>;
}
```


## Source

### hooks/use-mobile.ts

```ts
import * as React from "react";

const MOBILE_BREAKPOINT = 768;

export function 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;
}
```



## Usage

A hook that tracks whether the viewport is mobile-sized.

```tsx
import { useIsMobile } from "@/hooks/use-mobile";
```

