useMediaQuery
zyeon/use-media-queryFreeHook
An SSR-safe hook that subscribes to a CSS media query and returns whether it currently matches.
Install it
npx shadcn@latest add https://ui.zyeon.ai/r/use-media-query.jsonSource
1"use client"23import * as React from "react"45export interface UseMediaQueryOptions {6 /** Snapshot used during SSR and before hydration. Defaults to false. */7 serverFallback?: boolean8}910/**11 * Subscribe to a CSS media query and return whether it currently matches.12 * `useSyncExternalStore` wires `matchMedia`, an external data source, into the13 * React tree: subscribe attaches the `change` listener of `matchMedia(query)`,14 * getSnapshot reads `.matches`, and getServerSnapshot returns `serverFallback`15 * while rendering on the server. All three are new closures whenever `query`16 * changes, so a changing `query` unsubscribes from the old `matchMedia` and17 * subscribes to the new one on its own — no hand-written `useEffect`, no18 * dependency array, and no `setState` in an effect body.19 *20 * `useReducedMotion` in this repo's `animated-text.tsx` is this hook specialised21 * to a single query (`prefers-reduced-motion: reduce`) with `serverFallback`22 * pinned to `false`.23 */24export function useMediaQuery(query: string, options: UseMediaQueryOptions = {}): boolean {25 const { serverFallback = false } = options2627 const subscribe = React.useCallback(28 (callback: () => void) => {29 if (typeof window === "undefined") return () => {}30 const mql = window.matchMedia(query)31 mql.addEventListener("change", callback)32 return () => mql.removeEventListener("change", callback)33 },34 [query],35 )3637 const getSnapshot = React.useCallback(() => window.matchMedia(query).matches, [query])38 const getServerSnapshot = React.useCallback(() => serverFallback, [serverFallback])3940 return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)41}4243export default useMediaQuery
Files it writes
More from zyeon
All 893 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAsyncuse-async | zyeon | Hooks | Free | no deps | |
| useBatteryuse-battery | zyeon | Hooks | Free | no deps | |
| useBroadcastChanneluse-broadcast-channel | zyeon | Hooks | Free | no deps | |
| useClickOutsideuse-click-outside | zyeon | Hooks | Free | no deps | |
| useClipboardPasteuse-clipboard-paste | zyeon | Hooks | Free | no deps | |
| useControllableStateuse-controllable-state | zyeon | Hooks | Free | no deps | |
| useCookieuse-cookie | zyeon | Hooks | Free | no deps | |
| useCopyToClipboarduse-copy-to-clipboard | zyeon | Hooks | Free | no deps |
