Do you rely on window
event listener in React?
Did you ever forget to remove the listener?
Not anymore!
useEventListener
to the rescue:
import { useEffect } from 'react'
export default function useEventListener(eventName, listener) {
useEffect(() => {
window.addEventListener(eventName, listener)
return () => {
window.removeEventListener(eventName, listener)
}
}, [eventName, listener])
}
Usage:
useEventListener('resize', handleResize)