useBreakpoint.tsx39 lines · main
| 1 | 'use client' |
| 2 | |
| 3 | import { useState } from 'react' |
| 4 | import { useIsomorphicLayoutEffect, useWindowSize } from 'react-use' |
| 5 | |
| 6 | /** |
| 7 | * Map of Tailwind default breakpoint values. Allows setting a value by |
| 8 | * Tailwind breakpoint, so that it syncs up with CSS changes. |
| 9 | * |
| 10 | * Note Tailwind uses `min-width` logic, whereas we use `max-width` logic, so |
| 11 | * the values are offset by 1px. |
| 12 | * |
| 13 | * Source: |
| 14 | * https://tailwindcss.com/docs/responsive-design |
| 15 | */ |
| 16 | const twBreakpointMap = { |
| 17 | sm: 639, |
| 18 | md: 767, |
| 19 | lg: 1023, |
| 20 | xl: 1279, |
| 21 | '2xl': 1535, |
| 22 | } |
| 23 | |
| 24 | export function useBreakpoint(breakpoint: number | keyof typeof twBreakpointMap = 'lg') { |
| 25 | const [isBreakpoint, setIsBreakpoint] = useState(false) |
| 26 | const { width } = useWindowSize() |
| 27 | |
| 28 | const _breakpoint = typeof breakpoint === 'string' ? twBreakpointMap[breakpoint] : breakpoint |
| 29 | |
| 30 | useIsomorphicLayoutEffect(() => { |
| 31 | if (width <= _breakpoint) { |
| 32 | setIsBreakpoint(true) |
| 33 | } else { |
| 34 | setIsBreakpoint(false) |
| 35 | } |
| 36 | }, [width]) |
| 37 | |
| 38 | return isBreakpoint |
| 39 | } |