DEV Community

Cover image for React Custom Hook: useEventListener
Sergey Leschev
Sergey Leschev

Posted on

React Custom Hook: useEventListener

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useEventListener" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

import { useState } from "react"
import useEffectOnce from "./useEffectOnce"

export default function EffectOnceComponent() {
    const [count, setCount] = useState(0)
    useEffectOnce(() => alert("Hi"))
    return (
        <>
            <div>{count}</div>
            <button onClick={() => setCount(c => c + 1)}>Increment</button>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

One of the major advantages of useEventListener is its flexibility. You can specify the event type, callback function, and even the element where the event listener should be attached. This flexibility allows you to tailor event handling to your specific needs, enhancing the reusability of your code.

The hook also takes advantage of the useRef hook to maintain a stable reference to the callback function. This ensures that the most up-to-date version of the callback is used, even if it changes during the component's lifecycle. This dynamic behavior enables you to handle events with precision and respond to changes in your application's state.

The useEventListener hook is a versatile tool that can be used in a wide range of scenarios. Whether you need to capture keyboard events, listen for scroll events, or interact with user input, this hook has got you covered. Its simplicity and elegance make it an ideal choice for any React project, from small-scale applications to large-scale enterprise solutions.

To demonstrate the power of useEventListener, consider the EventListenerComponent provided. It utilizes the hook to track the last key pressed by the user. With just a few lines of code, you can effortlessly handle keydown events and update the component's state accordingly. This example highlights the ease and effectiveness of useEventListener, showcasing its ability to simplify event-driven interactions in React applications.

import { useEffect, useRef } from "react"

export default function useEventListener(
    eventType,
    callback,
    element = window
) {
    const callbackRef = useRef(callback)
    useEffect(() => {
        callbackRef.current = callback
    }, [callback])
    useEffect(() => {
        if (element == null) return
        const handler = e => callbackRef.current(e)
        element.addEventListener(eventType, handler)
        return () => element.removeEventListener(eventType, handler)
    }, [eventType, element])
}
Enter fullscreen mode Exit fullscreen mode

Throughout this article series, we focused on one of the gems from the collection of React custom hooks – "useEventListener". This hook, sourced from the "react-custom-hooks" repository, revolutionizes how we work in our React applications.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4

Top comments (0)