useWindowSize

React hook to track the dimensions of the browser window.

Add the hook via the CLI:

npx @novajslabs/cli add useWindowSize

Or copy and paste the code into your project:

import { useState, useEffect } from 'react'

type WindowSize = {
  width: number
  height: number
}

export const useWindowSize = (): WindowSize => {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: window.innerWidth,
    height: window.innerHeight,
  })

  const handleResize = () => {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    })
  }

  useEffect(() => {
    window.addEventListener('resize', handleResize)

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

  return windowSize
}

React 16.8 or higher

  • Name
    width
    Type
    number
    Description

    The current width of the browser window in pixels.

  • Name
    height
    Type
    number
    Description

    The current height of the browser window in pixels.

import { useWindowSize } from './hooks/useWindowSize'

const App = () => {
  const { width, height } = useWindowSize()

  return <div className={`${width > 1200 ? 'w-96' : 'w-56'}`}>Some content</div>
}

export default App

Here are some use cases where this React hook is useful:

  • Dynamically resizing elements or components based on changes in the viewport size
  • Adapting the display of content or media based on the available screen space in a mobile-responsive website
  • Implementing conditional rendering of UI elements for different device sizes in a cross-platform application
  • Adjusting the positioning or alignment of elements based on changes in the browser window dimensions for improved user experience