Categories
JavaScript Answers

How to listen to window events from components with React.js?

Spread the love

Sometimes, we want to listen to window events from components with React.js.

In this article, we’ll look at how to listen to window events from components with React.js.

How to listen to window events from components with React.js?

To listen to window events from components with React.js, we call window.addEventListener in the useEffect callback.

For instance, we write

useEffect(() => {
  const onScroll = (event) => console.info("scrolling", event);

  window.addEventListener("scroll", onScroll);

  return () => {
    window.removeEventListener("scroll", onScroll);
  };
}, []);

to call the useEffect with a callback that calls window.addEventListener to listen to the scroll event on window.

We set the event listener to onScroll.

We call useEffect with an empty array to call the callback only when the component mounts.

Conclusion

To listen to window events from components with React.js, we call window.addEventListener in 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.