Unlike your React components, the event listeners they've created don't magically disappear after their UI unmounts from the DOM. Undisposed event listeners will linger in your browser to haunt future components. Be afraid.
For example, let's say you want to create a simple component that displays the instantaneous window width.
The first step is to create a function for setting some component state we'll call windowWidth
, then create a window event listener in the React lifecycle method componentDidMount()
with our new setter function as a callback
.
When the component first mounts, updateWindowSize()
is called directly. As the window size changes, the event listener we've created calls the same function as a callback.
Before the current component unmounts, our event listener must be removed from the global Window object
by utilizing the React lifecycle method componentWillUnmount()
.
All together the code is quite simple and can save you from a lot of potential headaches.