useBreakpoint.tsx 992 B

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