Custom Hooks
useToggle
import { useReducer } from 'react'
const useToggle = (initialValue = false) => useReducer(toggler, initialValue)
useEventListener
import { useRef, useEffect } from 'react'
const useEventListener = (eventName, handler, element = window /* , options = {} */) => {
const savedHandler = useRef()
// const { capture, passive, once } = options
useEffect(() => {
savedHandler.current = handler
}, [handler])
useEffect(() => {
if (!element || !element.addEventListener) {
// not supported
return
}
const eventListener = event => savedHandler.current(event)
// const opts = { capture, passive, once }
element.addEventListener(eventName, eventListener /* , opts */)
return () => {
element.removeEventListener(eventName, eventListener /* , opts */)
}
}, [eventName, element/* , capture, passive, once */])
}
Last updated