For a legacy app we are rewriting parts of web app with React piece by piece. Because of this can't remove junks of document listeners completely. There are lots of different components all over the page that have listeners on them. This is effecting react components performance.
For example; Material UI Toggle Menu, https://codesandbox.io/s/o9970jm69 Toggling menu is fast and responsive to your clicks in example. But for our web app because of these document event listeners, toggle behavior is not the same as the demo.
Is it possible to remove these document click listeners for React elements?
Or is there a way to get rid of from these listener for React components?
Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.
removeEventListener() The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.
According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use . detach() instead.
replaceChild(new_element, old_element); Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.
Solution #1 for jQuery events
You can use unbind to remove events. If you need know the event name or type, you can see with Chrome Dev Tools
Solution #2 Javascript events
Another method is capture the event and stop the propagation. You can use removeEventListener or set null the property event.
instead of trying to remove listeners, I suggest you don't attach them in the first place.
... can't remove junks of document listeners completely
since that is not an option, your second best bet is to modify the listeners so that they exit early if event.target
is part of react app (you can verify that by doing document.getElementById('#your-react-dom-root').contains(event.listener)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With