use-media-query
I was trying to find a simple useMediaQuery
react hook. The most popular solutions are
bloated (react-responsive 164kb, really?)
and the ones I like (for example use-media-query)
doesn't have Typescript support or uses context and providers
So I decided to make my own:
useMediaQuery.ts #
import { useState, useEffect } from "react";
export default function useMediaQuery(query: string) {
const queryList = window.matchMedia(query);
const [isMatch, setMatches] = useState(queryList.matches);
useEffect(() => {
const listener = (e: MediaQueryListEvent) => setMatches(e.matches);
queryList.addEventListener("change", listener);
return () => queryList.removeEventListener("change", listener);
}, [queryList]);
return isMatch;
}
It looks matchMedia is supported enough for my needs.
Tailwind #
Since we're unsing tailwind, I've added an utility function to work with the same sizes:
// Ensure it matches the tailwind configuration
// Currently we use the default config: https://tailwindcss.com/docs/breakpoints
const SCREENS = {
sm: "640px",
md: "768px",
lg: "1024px",
xl: "1280px",
} as const;
export type ScreenType = keyof typeof SCREENS;
export const isScreen = (type: ScreenType) => `(max-width: ${SCREENS[type]})`;
Usage #
No suprises:
const isMobile = useMediaQuery(isScreen("sm"));