DEV Community

Cover image for Custom React hook useWindowSize()
calag4n
calag4n

Posted on

Custom React hook useWindowSize()

Sooner, I needed to get the viewport width on a React app and I wanted it real time updated so I decided to make a hook to deal with it.

Here comes the whole code:

import React, { useEffect, useState } from "react"

const useWindowSize = () => {
  const [windowWidth, setWidth] = useState(undefined)
  const [windowHeight, setHeight] = useState(undefined)

  useEffect(() => {  
    const getSize = () => {
      setWidth(window.innerWidth)
      setHeight(window.innerHeight)
    }
    window.addEventListener('resize', getSize)
    getSize()

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

  return { windowWidth, windowHeight }
}

export default useWindowSize
Enter fullscreen mode Exit fullscreen mode

Some explanations

  const [windowWidth, setWidth] = useState(undefined)
  const [windowHeight, setHeight] = useState(undefined)
Enter fullscreen mode Exit fullscreen mode

I initialize the states with undefined that avoid some build errors and allow you to get rid of ๐Ÿ‘‡๏ธ

if (typeof window !== 'undefined'){
  // make stuff with window object
}
Enter fullscreen mode Exit fullscreen mode

As the component did mount, the getSize() function set the states with window.innerWidth and window.innerHeight

We also handle the event 'resize' on the window object with getSize() to keep track of the sizes anytime it could be changed.

Usage

This can be used in component as follow :

import React from 'react'
import useWindowSize from "path/to/useWindowSize"

const Header = () => {

  const {windowWidth} = useWindowSize()

  return (
    <header>
      {windowWidth < 700 ? (
        <MobileMenu/>
      ) : (
        <DesktopMenu/>
      )}      
    </header>
  )
}
Enter fullscreen mode Exit fullscreen mode

I would be pleased to read your comments, seeya ๐Ÿ‘‹๏ธ

Top comments (2)

Collapse
 
khangnd profile image
Khang

Simple and easy to understand. Thank you for sharing ๐Ÿ‘

Collapse
 
calag4n profile image
calag4n

Thank you. I hope it helps.