Created
May 21, 2020 17:06
-
-
Save alejovdev/a6928cbcbf72140c92e331a4c275b060 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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