Skip to content

Instantly share code, notes, and snippets.

@vczb
Created December 17, 2021 20:29
Show Gist options
  • Select an option

  • Save vczb/144b9de19f8ed4d08769399734226c5a to your computer and use it in GitHub Desktop.

Select an option

Save vczb/144b9de19f8ed4d08769399734226c5a to your computer and use it in GitHub Desktop.
useReziseWindow react custom hook
import { useEffect, useState } from 'react'
export default function useReziseWindow() {
const [windowWidth, setWindowWidth] = useState<number | null>()
useEffect(() => {
const onResize = () => {
setWindowWidth(window?.innerWidth)
}
window.addEventListener('resize', onResize)
return () => {
window.removeEventListener('resize', onResize)
}
}, [])
return windowWidth
}
@vczb
Copy link
Author

vczb commented Dec 17, 2021

example usage:

import { useEffect, useState } from 'react'
import useReziseWindow from 'hooks/use-rezise-window'
import * as S from './styles'

const Banner = () => {
  const windowWidth = useReziseWindow()

  const [isMobile, setIsMobile] = useState(false)

  useEffect(() => {
    if (windowWidth) {
      setIsMobile(windowWidth < 768)
    }
  }, [windowWidth])

  return (
    <>...</>
  )
}

export default Banner

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