Skip to content

Instantly share code, notes, and snippets.

@bartosjiri
Last active November 27, 2020 17:46
Show Gist options
  • Save bartosjiri/ef59dc26f4b17e1a72c6247d79035754 to your computer and use it in GitHub Desktop.
Save bartosjiri/ef59dc26f4b17e1a72c6247d79035754 to your computer and use it in GitHub Desktop.
React window size hook with resize listener

useWindowSize.js:

import {useState, useEffect} from 'react';

const REFRESH_TIMEOUT = 150;

const useWindowSize = () => {
  const getSize = () => ({
    width: window.innerWidth
      || document.documentElement.clientWidth
      || document.body.clientWidth,
    height: window.innerHeight
      || document.documentElement.clientHeight
      || document.body.clientHeight
  })

  const [windowSize, setWindowSize] = useState(getSize)

  useEffect(() => {
    let timeoutId = null

    const handleResize = () => {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => setWindowSize(getSize), REFRESH_TIMEOUT)
    }

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

  return windowSize
}

export default useWindowSize

Any component:

import React from "react"
import useWindowSize from "<path>/useWindowSize"

const Component = () => {
   let windowSize = useWindowSize()
  
  return (
    //...
  )
}

export default Component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment