Created
March 27, 2020 06:04
-
-
Save mannuelf/4917d0ab3e7883fce70347f38532bb32 to your computer and use it in GitHub Desktop.
React Hooks clean up function after running useEffect
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, useEffect } from 'react' | |
export default function WindowSize() { | |
const [[windowWidth, windowHeight], setWindowSize] = useState([window.innerWidth, window.innerHeight]) | |
const [visible, setVisible] = useState(false) | |
useEffect(() => { | |
let timeoutId | |
const handleResize = () => { | |
setWindowSize([window.innerWidth, window.innerHeight]) | |
setVisible(true) | |
clearTimeout(timeoutId) | |
timeoutId = setTimeout(() => setVisible(false), 500) | |
} | |
window.addEventListener('resize', handleResize) | |
return () => window.removeEventListener('resize', handleResize) // CLEAN UP FUNCTION | |
}, []) | |
return ( | |
<div className={`window-size ${visible ? '' : 'hidden'}`}> | |
WINDOW SIZE: {windowWidth} x {windowHeight} | |
</div> | |
) | |
} | |
// credits: https://scrimba.com/p/pKkkVU3/czN22yC9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment