Initial commit
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
# useIsMobile
|
||||
|
||||
Returns `true` when the viewport width is below a configurable breakpoint, and re-evaluates reactively on resize.
|
||||
|
||||
## Signature
|
||||
|
||||
```ts
|
||||
function useIsMobile(mobileBreakpoint?: number): boolean;
|
||||
```
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ------------------ | -------- | ------- | ------------------------------------------------------------ |
|
||||
| `mobileBreakpoint` | `number` | `1024` | Viewport width (px) at which the device is considered mobile |
|
||||
|
||||
## Usage
|
||||
|
||||
```tsx
|
||||
function Navbar() {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
return isMobile ? <MobileNav /> : <DesktopNav />;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Custom breakpoint
|
||||
const isTablet = useIsMobile(768);
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Uses `window.matchMedia` for the resize listener (more efficient than `resize` event polling).
|
||||
- Returns `false` during SSR (initial state is `undefined`, coerced via `!!`).
|
||||
- Client-only (`'use client'`).
|
||||
@@ -0,0 +1 @@
|
||||
export * from './useIsMobile';
|
||||
@@ -0,0 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
export function useIsMobile(mobileBreakpoint: number = 1024) {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${mobileBreakpoint - 1}px)`);
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < mobileBreakpoint);
|
||||
};
|
||||
mql.addEventListener('change', onChange);
|
||||
setIsMobile(window.innerWidth < mobileBreakpoint);
|
||||
return () => mql.removeEventListener('change', onChange);
|
||||
}, []);
|
||||
|
||||
return !!isMobile;
|
||||
}
|
||||
Reference in New Issue
Block a user