Categories
React

How to Register Event Handlers with React Hooks?

Spread the love

React hooks are the main way that we can create components.

Sometimes we have to register event handlers in our own components.

In this article, we’ll look at how to register native event handlers within React components.

Registering Native Event Handlers

We can register native event handlers with vanilla JavaScript.

We can call the addEventListener method with a DOM element, window or document to register an event handler.

For instance, we can write:

import React, { useEffect } from "react";

export default function App() {
  const handleUserKeyPress = (e) => {
    console.log(e.which);
  };

  useEffect(() => {
    window.addEventListener("keydown", handleUserKeyPress);

    return () => {
      window.removeEventListener("keydown", handleUserKeyPress);
    };
  }, []);

  return <div></div>;
}

to register an event handler for the window ‘s keydown event.

We just call addEventListener to add the event listener.

And to remove the event listener when the component unmounts, we return a function that calls window.removeListener to remove the keydown event listener.

The function we return in the useEffect callback only runs when the component unmounts.

The 2nd argument we passed into the useEffect hook is an empty array, so the useEffect callback runs only when we mount the component.

This should only be used for objects like window and document which aren’t part of the component since we can assign event handlers for them by assigning the correct props for the event handler.

Conclusion

We can register native event handlers for window or document in the useEffect gook by calling addEventListener .

And to remove the event listener when the component unmounts, we return a function that calls removeEventListener to in the useEffect callback to remove the event listener when the component unmounts.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *