4 mins read


Custom React Hook for Event Listening

Learn how to create a custom React hook for event listening. Simplify event handling in your React applications with this reusable hook, offering flexibility and control over various types of events.


Introduction to useEventListener

Event handling is a crucial aspect of building interactive web applications. In React, managing events efficiently is essential for providing a smooth user experience. React's built-in useEffect hook allows developers to perform side effects in functional components, making it a suitable choice for implementing event listeners. However, creating reusable event listener logic can sometimes be repetitive and error-prone.

To address this issue, developers often turn to custom hooks. Custom hooks encapsulate reusable logic, promoting code reusability and maintainability. In this tutorial, we'll explore how to create a custom React hook for event listening, allowing us to easily add event listeners to functional components.

Understanding the Requirements

Before we dive into implementation, let's define the requirements for our custom hook:

  • Input: The custom hook should accept two parameters:
    • type: The type of event to listen for (e.g., "keydown", "keyup", "online").
    • callback: The callback function to be executed when the event occurs.
  • Output: The hook should add an event listener when the component mounts and remove it when the component unmounts.
  • Flexibility: It should support various types of events, such as keyboard events (keydown, keyup), network events (online, offline), and common events (visibilitychange).

Implementation

import { useEffect } from "react";
 
type KeyboardEventTypes = "keydown" | "keyup" | "keypress";
type NetworkEventTypes = "online" | "offline";
type CommonType = "visibilitychange";
type EventType = KeyboardEventTypes | NetworkEventTypes | CommonType;
type CallbackType = KeyboardEvent | Event;
type Args = {
  type: EventType;
  callback: (e: CallbackType) => void;
};
 
/**
 * Creates an event listener for the specified event type and callback function.
 *
 * @param {Args} Args - An object containing the type and callback.
 * @param {string} Args.type - The type of event to listen for.
 * @param {Function} Args.callback - The function to be called when the event occurs.
 * @return {void} - This function does not return anything.
 */
const useEventListener = ({ type, callback }: Args) => {
  useEffect(() => {
    window.addEventListener(type, callback);
    return () => window.removeEventListener(type, callback);
  }, [type, callback]);
};
 
export default useEventListener;

Usage

Now that we have our custom hook implemented, let's see how we can use it in a React component:

import React from "react";
import useEventListener from "./useEventListener";
 
const MyComponent = () => {
  // Example: Adding a keyboard event listener
  useEventListener({
    type: "keydown",
    callback: (event) => {
      console.log("Key pressed:", event.key);
    },
  });
 
  // Example: Adding a network event listener
  useEventListener({
    type: "online",
    callback: () => {
      console.log("Online");
    },
  });
 
  // Example: Adding a visibility change event listener
  useEventListener({
    type: "visibilitychange",
    callback: () => {
      console.log("Visibility changed");
    },
  });
 
  return <div>My Component</div>;
};
 
export default MyComponent;

Conclusion

Creating custom hooks for common tasks, such as event listening, can significantly improve code readability, reusability, and maintainability in React applications. By encapsulating event listener logic within a custom hook, developers can easily add and manage event handling behavior across their applications. With the useEventListener hook we've implemented, handling various types of events becomes a breeze, providing a more efficient and structured approach to event management in React components.