Categories
React Answers

How to register event with React useEffect hooks?

Spread the love

Sometimes, we want to register event with React useEffect hooks.

In this article, we’ll look at how to register event with React useEffect hooks.

How to register event with React useEffect hooks

To register event with React useEffect hooks, we can call the window.addEventListener method in the useEffect callback.

For instance, we write

//...

const Comp = () => {
  const [userText, setUserText] = useState("");
  const handleUserKeyPress = useCallback((event) => {
    const { key, keyCode } = event;
    if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
      setUserText((prevUserText) => `${prevUserText}${key}`);
    }
  }, []);

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

  return (
    <div>
      <blockquote>{userText}</blockquote>
    </div>
  );
};

to create the userText state with the useState hook.

Then we creatr the handleUserKeyPress function that checks for the key that’s pressed.

And we call setUserText to append the key pressed to userText.

Then we call useEffect with a callback that calls window.addEventListener to listen to the keydown event.

And handleUserKeyPress is called when the keydown event is triggered.

The useEffect callback is run when handleUserKeyPress changes.

We return a function that calls window.removeEventListener to remove the keydown listener when handleUserKeyPress changes.

Conclusion

To register event with React useEffect hooks, we can call the window.addEventListener method in the useEffect callback.

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 *