I know this might flag as a duplicate solution but solution on stack overflow is not working for me.
Problem:
(node:5716) MaxListenersExceededWarning
This is the recommended way to add and remove event listeners within React Components - using LifeCycle methods.
import { Component } from 'react';
class Example extends Component {
constructor(props) {
super(props);
this.state = {
windowWidth: window.innderWidth,
};
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize = () => {
this.setState({ windowWidth: window.innerWidth });
}
render() {
return (
Current window width: {this.state.windowWidth}
);
}
}
It's important to remember that window is within the global execution context. Therefore every time you add an event listener, you're asking the global scope to
resizeIf you never tell the global scope to remove those listeners, then the global memory - as allocated by your browser settings - will slowly evaporate and crash your browser & application, or the client's browser if already in production. One must be VERY careful and VERY aware when they manipulate global memory.
If you want to understand (if you don't already) WHY the lifecycle methods in React Component's work, I would highly recommend you look here at React's Reconciliation lifecycle. One can't accurately call themselves a "React Developer" and not be intimately familiar with Reconciliation.
Note This Component is using babel to transpile parts of the code: import, and assigned custom method handleResize with only using arrow functions. If you need assistance in setting up the environment, you can refer to this blog post i wrote that should make it understandable.
Good luck.