Should I remove "once" registered event listeners during cleanup in React

Viewed 414

Should I remove event listeners registered like this:

window.addEventListener('resize', callback, { once: true });

During cleanup in React like this:

useEffect(() => {
  return () => {
    window.removeEventListener('resize', callback, { once: true });
  };
}, []);

Or is it completely unnecessary since it will get removed automatically after it has been invoked once? The possibility of the user closing the browser before the event listener gets invoked is small but it's there. So I'm currently thinking that I should remove it during cleanup even though the event listener will get removed automatically after it has been called.

1 Answers

the documentation looks the next:

Once is a Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

But in the case when the callback was not called yet and you unmount your component and mount again. You will have two identical listeners.

As a result you have to remove listener if it was not called and don't need remove listener if it was called

Related