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.

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 *