Categories
React Answers

Hoe to Register Event Handlers within the React useEffect Hook?

Spread the love

Sometimes, we want to registrar events listeners within the useEffect hook.

In this article, we’ll look at how to registrar events listeners within the useEffect hook.

Register Event Handlers within the React useEffect Hook

We can register events within the useEffect callback.

For instance, we can write:

const App = () => {
  const [userText, setUserText] = useState('');

  const handleUserKeyPress = useCallback(event => {
    const { key, keyCode } = event;
    if (keyCode === 32) {
      setUserText(prevUserText => `${prevUserText}${key}`);
    }
  }, []);

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

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

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

We listen to the keypress event on the window.

If we press the space key, then the key code will be registered.

Then we can use that to append the state string with the key text.

We just keep appending the key code to the state string.

Conclusion

We can register events within the useEffect callback.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.