Optimise the event handling of your React components by using the useEvent
hook.
While using the EventListener API, you will need to use the useEffect
hook to update the event listener. but, not handling the cleanup may cause slowing down of the project.
In this way even the simplest callback needs atleast 3 lines of code. Using the hook helpd to maintain a clean code without worring about the cleanup.
The hooks requires three parameters - event
, callback
and element
(optional). The Element is window
by default, but you can use any React Element refer.
use-event.js
import { useEffect, useRef } from 'react'
/**
* Hook to use event listener
* @param event - Window event name
* @param callback - Callback function
* @param element - Element to attach event listener to
*/
export function useEvent(event, callback, element) {
// Create a ref that stores handler
const handler = useRef()
useEffect(() => {
// Define the listening target
const targetElement = element?.current || window
if (!(targetElement && targetElement.addEventListener)) return
// Update saved handler if necessary
if (handler.current !== callback) handler.current = callback
// Add event listener
const eventListener = (event) => {
if (!!handler?.current) handler.current(event)
}
targetElement.addEventListener(event, eventListener)
// cleanup
return () => {
targetElement.removeEventListener(event, eventListener)
}
}, [event, element, callback])
}
export default useEvent
import { useState } from 'react'
import useEvent from 'hooks/use-event'
...
const [value, setValue] = useState('')
useEvent('scroll', (e) => setValue(e.target.scrollTop))
...
<div>Scroll top : {value}</div>