[FIXED] Electron-React: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 21 updateDeviceList listeners added to [EventEmitter]

Issue

I tried searching all over in understanding the cause of this,
and i think i have the tip of the string,
i use usb detection do detect when usb devices are connected,

usbDetect.on('add', () => sendDeviceListToGUI(1));

within this function i do the following

const sendDeviceListToGUI= async (status: number) => {
  mainWindow?.webContents.send('updatingDeviceList', status);
  const list = await getConnectedDeviceArray();
  mainWindow?.webContents.send('updateDeviceList', list);
};

i assume that the event pile up whenever a device is connected or disconnected,

(node:41276) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 21 updateDeviceList listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
(Use `TestApp --trace-warnings ...` to show where the warning was created)
(node:41276) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 21 updatingDeviceList listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit

i tried increasing the limit but with no luck, i feel that i need to resolve the event like with promises.

(also the –trace-warnings … doesn’t work any idea why)

Solution

I found the problem, i have this call in my react file, since i use functional components every time i rerender the component, it registers a new listener.

window.myapiAPI.updateDeviceList()

i think there is an option to solve it with hooks, and make sure the hook runs once.
but for now in my preload file i remove all listeners before assigning a new one.

ipcRenderer.removeAllListeners('updateDeviceList');

UPDATE 2

i wrapped all the functions in a useEffect hook that runs on the first render.

useEffect(() => {
    window.myAPI.message((message: string) => {
      AppToaster.show({
        message,
        intent: Intent.WARNING,
      });
    });
  }, []);

Answered By – 2BC.Wasabi

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published