V
Custom Background

useBreakpoint

Get the current breakpoint, based on Tailwind CSS breakpoints

import React from 'react'
import tailwindConfig from '@/tailwind.config'
import resolveConfig from 'tailwindcss/resolveConfig'

const {
  theme: { screens },
} = resolveConfig(tailwindConfig)

type Screen = keyof typeof screens

// Define breakpoints based on Tailwind's default breakpoints
const breakpoints = Object.fromEntries(
  Object.entries(screens).map(([key, value]) => [key, parseInt(value)]),
) as Record<Screen, number>

const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)

type Breakpoint = keyof typeof breakpoints

export const useBreakpoint = () => {
  const [windowWidth, setWindowWidth] = React.useState(0)

  React.useEffect(() => {
    const handleResize = () => setWindowWidth(window.innerWidth)

    handleResize()

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  const isGreaterThan = (breakpoint: Breakpoint) =>
    windowWidth > breakpoints[breakpoint]

  const isLessThan = (breakpoint: Breakpoint) =>
    windowWidth < breakpoints[breakpoint]

  const customBreakpoints = Object.entries(screens).reduce(
    (acc, [key]) => ({
      ...acc,
      [`is${capitalize(key)}`]: isGreaterThan(key as Breakpoint),
      [`isMax${capitalize(key)}`]: isLessThan(key as Breakpoint),
    }),
    {},
  ) as Record<`is${Capitalize<Screen>}` | `isMax${Capitalize<Screen>}`, boolean>

  return {
    windowWidth,
    ...customBreakpoints
  }
}