use-media-query
efferd-/use-media-queryFreeHook
Use media query hook.
Live preview
live · rendered by the registry
Rendered by efferd on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add http://efferd.com/r/use-media-query.jsonSource
1"use client";2import { useEffect, useState } from "react";34function getDevice(): "mobile" | "tablet" | "desktop" | null {5 if (typeof window === "undefined") {6 return null;7 }89 if (window.matchMedia("(min-width: 1024px)").matches) {10 return "desktop";11 }1213 if (window.matchMedia("(min-width: 640px)").matches) {14 return "tablet";15 }1617 return "mobile";18}1920function getDimensions() {21 if (typeof window === "undefined") {22 return null;23 }2425 return { width: window.innerWidth, height: window.innerHeight };26}2728export function useMediaQuery() {29 const [device, setDevice] = useState<"mobile" | "tablet" | "desktop" | null>(30 null31 );32 const [dimensions, setDimensions] = useState<{33 width: number;34 height: number;35 } | null>(null);3637 useEffect(() => {38 const checkDevice = () => {39 setDevice(getDevice());40 setDimensions(getDimensions());41 };4243 // Initial detection44 checkDevice();4546 // Listener for windows resize47 window.addEventListener("resize", checkDevice);4849 // Cleanup listener50 return () => {51 window.removeEventListener("resize", checkDevice);52 };53 }, []);5455 return {56 device,57 width: dimensions?.width,58 height: dimensions?.height,59 isMobile: device === "mobile",60 isTablet: device === "tablet",61 isDesktop: device === "desktop",62 };63}
Files it writes
More from efferd
All 201 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| use-copy-to-clipboarduse-copy-to-clipboard | efferd | Hooks | Free | no deps | |
| use-keypressuse-keypress | efferd | Hooks | Free | no deps | |
| use-scrolluse-scroll | efferd | Hooks | Free | no deps |
