useScreen


Easily retrieve window.screen object with this Hook React which also works onResize.

Usage

import { useScreen } from 'reactchemy'

export default function Component() {
   const screen = useScreen()

   return (
    <div>
      The current window dimensions are:{' '}
      <code>
        {JSON.stringify({ width: screen?.width, height: screen?.height })}
      </code>
    </div>
   )
}

Hook

import { useState } from 'react'

import { useEventListener, useIsomorphicLayoutEffect } from 'reactchemy'

export function useScreen() {
   const getScreen = () => {
      if (typeof window !== 'undefined' && window.screen)
         return window.screen

      return undefined
   }

   const [screen, setScreen] = useState<Screen | undefined>(getScreen())

   function handleSize() {
      setScreen(getScreen())
   }

   useEventListener('resize', handleSize)

   // Set size at the first client-side load
   useIsomorphicLayoutEffect(() => {
      handleSize()
   }, [])

   return screen
}