UseMedia
guarahooks/use-mediaFreeHook
Checks if the current window matches a media query.
Install it
npx shadcn@latest add https://guarahooks.com/r/use-media.jsonSource
1'use client';23import { useEffect, useState } from 'react';45const getInitialState = (query: string, defaultState?: boolean): boolean => {6 const isBrowser = typeof window !== 'undefined';78 if (!query || typeof query !== 'string') {9 throw new Error('useMedia: query should be a non-empty string.');10 }1112 if (defaultState !== undefined) {13 return defaultState;14 }1516 if (isBrowser) {17 return window.matchMedia(query).matches;18 }1920 if (process.env.NODE_ENV !== 'production') {21 console.warn(22 '`useMedia` When server side rendering, defaultState should be defined to prevent a hydration mismatches.',23 );24 }2526 return false;27};2829export function useMedia(query: string, defaultState?: boolean): boolean {30 const [state, setState] = useState<boolean>(() =>31 getInitialState(query, defaultState),32 );3334 useEffect(() => {35 if (!query || typeof query !== 'string') {36 throw new Error('useMedia: query should be a non-empty string.');37 }3839 let mounted = true;40 const mql = window.matchMedia(query);4142 const onChange = () => {43 if (!mounted) {44 return;45 }46 setState(!!mql.matches);47 };4849 mql.addEventListener('change', onChange);50 setState(mql.matches);5152 return () => {53 mounted = false;54 mql.removeEventListener('change', onChange);55 };56 }, [query]);5758 return state;59}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
