Published on

useEventlistner Hook React

useEventlistner Hook React

useEventlistner Hook React

useEventlistner Code and Usage

useEventlistner is a hook can be used to easily add event listeners to elements, This hook encapsulates the process of adding and removing event listeners, making it more convenient and efficient.

import { useEffect } from "react";

const useEventListener = (eventName, handler, element = window) => {
  useEffect(() => {
    // Make sure the element supports addEventListener
    const isSupported = element && element.addEventListener;
    if (!isSupported) return;

    // Add the event listener
    element.addEventListener(eventName, handler);

    // Clean up the event listener on component unmount
    return () => {
      element.removeEventListener(eventName, handler);
    };
  }, [eventName, handler, element]);
};

// Usage in a component
function App() {
  const handleKeyPress = (event) => {
    if (event.key === "Enter") {
      console.log("Enter key pressed");
    }
  };

  // Using the useEventListener hook
  useEventListener("keydown", handleKeyPress);

  return (
    <div className="App">
      <h1>Event Listener Example</h1>
      <p>Press the Enter key and check the console.</p>
    </div>
  );
}

export default App;