showing results for - "add event listener react hooks"
Mariangel
31 Apr 2019
1import { useEffect } from "react"
2
3export default function useEvent(event, handler, passive = false) {
4  useEffect(() => {
5    // initiate the event handler
6    window.addEventListener(event, handler, passive)
7
8    // this will clean up the event every time the component is re-rendered
9    return function cleanup() {
10      window.removeEventListener(event, handler)
11    }
12  })
13}