Search code examples
node.jsreactjselectroneventemitter

Event Emitter memory leak because of ReactJS Rerendering


I hope you're having a nice day ✌ Thanks for helping in advance.

I'm building a web browser with ElectronJS and React. I'm using ipcMain and ipcRenderer to send events between the backend and the frontend, they're just children of the EventEmitter class.

The issue I'm dealing with is EventEmitter leaks. My React frontend sends an event, and the backend returns data. React then assigns this data to it's state which causes a re-render which then creates another event listener. This creates a bunch of event listeners and then I get memory leak errors.

This is an example of my React component

export const CoreLayout = props => {

  const [tablist, setTablist] = useState([]);
  window.ipcRenderer.on('receive-tabs', (_, data) => {
    setTablist(data);
  });

  console.log('rerender2')

  return (
    <div className="flex flex-col w-full min-h-screen bg-night-600">
      <Header tablist={tablist} isMaximized={props.isMaximized} />
    </div>
  )

}

Solution

  •   useEffect(()=>{
        const listener= (_, data) => {
          setTablist(data);
        };
        window.ipcRenderer.on('receive-tabs', listener);
        
        return ()=>{
          window.ipcRenderer.removeListener('receive-tabs', listener);
        }
      });