ScreenSizeProvider.tsx raw

   1  import { createContext, useContext, useEffect, useState } from 'react'
   2  
   3  type TScreenSizeContext = {
   4    isSmallScreen: boolean
   5    isTabletScreen: boolean
   6    isNarrowDesktop: boolean
   7    isLargeScreen: boolean
   8    canUseDoublePane: boolean
   9  }
  10  
  11  const ScreenSizeContext = createContext<TScreenSizeContext | undefined>(undefined)
  12  
  13  export const useScreenSize = () => {
  14    const context = useContext(ScreenSizeContext)
  15    if (!context) {
  16      throw new Error('useScreenSize must be used within a ScreenSizeProvider')
  17    }
  18    return context
  19  }
  20  
  21  export function ScreenSizeProvider({ children }: { children: React.ReactNode }) {
  22    const [isSmallScreen, setIsSmallScreen] = useState(() => window.innerWidth <= 768)
  23    const [isTabletScreen, setIsTabletScreen] = useState(
  24      () => window.innerWidth >= 480 && window.innerWidth <= 768
  25    )
  26    const [isNarrowDesktop, setIsNarrowDesktop] = useState(
  27      () => window.innerWidth > 768 && window.innerWidth <= 1024
  28    )
  29    const [isLargeScreen, setIsLargeScreen] = useState(() => window.innerWidth >= 1280)
  30    const [canUseDoublePane, setCanUseDoublePane] = useState(() => window.innerWidth > 1024)
  31  
  32    useEffect(() => {
  33      const handleResize = () => {
  34        const width = window.innerWidth
  35        setIsSmallScreen(width <= 768)
  36        setIsTabletScreen(width >= 480 && width <= 768)
  37        setIsNarrowDesktop(width > 768 && width <= 1024)
  38        setIsLargeScreen(width >= 1280)
  39        setCanUseDoublePane(width > 1024)
  40      }
  41  
  42      window.addEventListener('resize', handleResize)
  43      return () => window.removeEventListener('resize', handleResize)
  44    }, [])
  45  
  46    return (
  47      <ScreenSizeContext.Provider
  48        value={{
  49          isSmallScreen,
  50          isTabletScreen,
  51          isNarrowDesktop,
  52          isLargeScreen,
  53          canUseDoublePane
  54        }}
  55      >
  56        {children}
  57      </ScreenSizeContext.Provider>
  58    )
  59  }
  60