Skip to content

Instantly share code, notes, and snippets.

@jeremy-code
Created May 26, 2026 05:47
Show Gist options
  • Select an option

  • Save jeremy-code/c5db4dd34f36288361fe863e8b55a3e7 to your computer and use it in GitHub Desktop.

Select an option

Save jeremy-code/c5db4dd34f36288361fe863e8b55a3e7 to your computer and use it in GitHub Desktop.
useBreakpoint.tsx
import { useSyncExternalStore } from "react";
type Breakpoint = "sm" | "md" | "lg" | "xl" | "2xl";
type BreakpointWithUtility = Breakpoint | `max-${Breakpoint}`;
const useBreakpoint = (breakpoint: BreakpointWithUtility) => {
const breakpointValue = window
.getComputedStyle(document.body)
.getPropertyValue(
`--breakpoint-${breakpoint.startsWith("max-") ? breakpoint.slice("max-".length) : breakpoint}`,
);
const mediaQueryList =
breakpoint.startsWith("max-") ?
window.matchMedia(`(width < ${breakpointValue})`)
: window.matchMedia(`(width >= ${breakpointValue})`);
const matches = useSyncExternalStore(
(onStoreChange) => {
mediaQueryList.addEventListener("change", onStoreChange);
return () => mediaQueryList.removeEventListener("change", onStoreChange);
},
() => mediaQueryList.matches,
);
return matches;
};
export { useBreakpoint };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment