Created
May 26, 2026 05:47
-
-
Save jeremy-code/c5db4dd34f36288361fe863e8b55a3e7 to your computer and use it in GitHub Desktop.
useBreakpoint.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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