Skip to content

Instantly share code, notes, and snippets.

@mannuelf
Created March 27, 2020 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mannuelf/4917d0ab3e7883fce70347f38532bb32 to your computer and use it in GitHub Desktop.
Save mannuelf/4917d0ab3e7883fce70347f38532bb32 to your computer and use it in GitHub Desktop.
React Hooks clean up function after running useEffect
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