Skip to content

Instantly share code, notes, and snippets.

@hexcowboy
Last active September 4, 2023 16:03
Show Gist options
  • Save hexcowboy/e6ed5d2e53e875823b6adccd38105d8a to your computer and use it in GitHub Desktop.
Save hexcowboy/e6ed5d2e53e875823b6adccd38105d8a to your computer and use it in GitHub Desktop.
React Typescript `useBreakpoint` hook

This react typescript hook will work in tandem with your tailwind config. You can also remove the tailwind references to make it work without.

It is recommended to place this in a folder like hooks/use-breakpoint.ts or src/hooks/use-breakpoint, or next to any other hooks you have defined.

// returns true if size is larger than the `md` breakpoint
const isMdOrLarger = useBreakpoint('md');
// returns true if the window size is less than the `lg` breakpoint
const isBelowLg = useBreakpoint('lg', 'max');
import { useEffect, useState } from "react";
import resolveConfig from "tailwindcss/resolveConfig";
import tailwindConfig from "@/../tailwind.config.js";
const fullConfig = resolveConfig(tailwindConfig);
type Size = "xs" | "sm" | "md" | "lg" | "xl" | "2xl";
const defaultScreens = {
xs: "0px",
sm: "640px",
md: "768px",
lg: "1024px",
xl: "1280px",
"2xl": "1536px",
};
type Direction = "min" | "max";
const screens = { ...defaultScreens, ...fullConfig.theme?.screens };
// This hook returns true if the screen size is greater than the given size when 'min' is true,
// or if the screen size is less than the given size when 'max' is true.
export const useBreakpoint = (size: Size, direction: Direction = "min") => {
const [isScreen, setIsScreen] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(
`(${direction}-width: ${screens[size]})`
);
const listener = () => setIsScreen(mediaQuery.matches);
mediaQuery.addEventListener("change", listener);
listener();
return () => mediaQuery.removeEventListener("change", listener);
}, [size, direction]);
return isScreen;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment