Memory leak when emitting an event after menu click in Electron app

Viewed 449

I'm currently building a desktop application with Electron and React.

Right now I'm adding a menu feature which toggles the dark mode of the app. In my React app, I'm using a hook which toggles the dark mode. I want to trigger that React hook right after the user has clicked on the menu item.

This is what I've done so far:

menu.ts:

buildDefaultTemplate() {
    const templateDefault = [
      {
        label: '&File',
        submenu: [
          {
            label: '&Open',
            accelerator: 'Ctrl+O',
          },
          {
            label: '&Toggle Dark Mode',
            accelerator: 'Ctrl+T',
            click: () => {
              this.mainWindow.webContents.send('toggle-dark-mode', {
                message: 'Toggle successful!',
              });
            },
          },
          {
            label: '&Close',
            accelerator: 'Ctrl+W',
            click: () => {
              this.mainWindow.close();
            },
          },
        ],
      },
]

Dashboard.tsx:

export default function Dashboard(): ReactElement {
  const { username } = os.userInfo();
  const { toggleColorMode } = useColorMode();

  useEffect(() => {
    ipcRenderer.on('toggle-dark-mode', () => {
      toggleColorMode();
    });
  }, [toggleColorMode]);

It works fine toggling it. But after repeating the operation a number of times, I get this warning: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 toggle-dark-mode listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit

I've seen a similar post but the answer wasn't satisfying. The suggestion there was to simply stop listening to events, which I think would be difficult in my case.

I'm looking for a way to unsubscribe to the event after the toggle has been successful.

1 Answers

Try setting up the toggle-dark-mode event handler once when you start your Electron app.

Your code doesn't need to be in the ready event even.

Related