You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A performant, SSR-safe React hook for tracking media queries using `useSyncExternalStore`. Optimized for Next.js and React 18+ with support for legacy browsers.
4
+
5
+
## Basic Usage
6
+
7
+
Perfect for simple responsive logic in client components.
return<div>{isMobile ?'Viewing on Mobile':'Viewing on Desktop'}</div>;
16
+
}
17
+
```
18
+
19
+
## Features
20
+
21
+
- ⚡ **React 18 Ready**: Uses `useSyncExternalStore` to prevent "tearing" and ensure consistency.
22
+
- 🌐 **SSR/Next.js Compatible**: Handles hydration gracefully with customizable fallbacks.
23
+
- ⏱️ **Built-in Debounce**: Optional delay to prevent excessive re-renders during window resizing.
24
+
- 🔄 **Legacy Support**: Automatic fallback for browsers not supporting `addEventListener` on `matchMedia`.
25
+
- 🎣 **Event Callback**: Integrated `onChange` listener for side effects.
26
+
27
+
## Advanced Example: Theming with `prefers-color-scheme`
28
+
29
+
To prevent **Flash of Unstyled Content (FOUC)** or layout shifts in Next.js, you can sync the server-side state (derived from cookies or user-agent) with the hook using the `fallback` option.
30
+
31
+
```jsx
32
+
// app/page.js (Server Component)
33
+
import { cookies } from'next/headers';
34
+
importThemeWrapperfrom'./ThemeWrapper';
35
+
36
+
exportdefaultfunctionPage() {
37
+
// Read the saved theme from cookies to ensure the server renders the correct UI
0 commit comments