Skip to content

Instantly share code, notes, and snippets.

@alejovdev
Created May 21, 2020 17:06
Show Gist options
  • Save alejovdev/a6928cbcbf72140c92e331a4c275b060 to your computer and use it in GitHub Desktop.
Save alejovdev/a6928cbcbf72140c92e331a4c275b060 to your computer and use it in GitHub Desktop.
import React, { useState, useLayoutEffect, useRef } from 'react'
function MyComponent() {
const [windowSize, _setWindowSize] = useState([
window.innerWidth,
window.innerHeight,
])
const windowSizeRef = useRef(windowSize)
const setWindowSize = (value) => {
windowSizeRef.current = value
_setWindowSize(value)
}
// Here we can normally use setWindowSize([x,y]) and windowSize
useLayoutEffect(() => {
function onWindowResize(event) {
// You can access the state value like this
let windowSizeValue = windowSizeRef.current
// And set the state value like this
setWindowSize([window.innerWidth, window.innerHeight])
}
window.addEventListener('resize', onWindowResize)
return () => {
window.removeEventListener('resize', onWindowResize)
}
}, [])
return (
<div>
Hi There, screen is {windowSize[0]} x {windowSize[1]}
</div>
)
}
export default MyComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment