This has been on my mind for a few days now.
As per the docs, React has synthetic event system, which is a a cross-browser wrapper around the browser's native event
. Going through the docs, is my understanding correct that the custom (synthetic) event system, isn't about efficiency but rather cross-browser compatibility.
In other words, React still appends the event to the element rather than the more efficient approach of event-delegation on the parent element?
I also noticed this in Firefox Inspector which raised the initial curiosity.
The reason for asking the question is that I am working on an app where a user maybe able to select a thousand elements & drag them around the screen, so eventually event delegation is going to come up.
Alright, you perhaps already figured everything on your own, but as I asked myself the same questions, I figured I'd leave this here in case someone else is curious about not only using React but also getting an idea about how it works.
So, I'm not entirely sure about your question (especially the "append the event to element" part) but:
Consequently, you first need to bring the events up to the virtual DOM, compute your changes there and dispatch them to the representation of components in the virtual DOM, then bring the relevant changes back down to be reflected in the DOM appropriately.
Carrying changes up to the virtual DOM is effectively done by top-level delegation. This means that React itself listens to all events at a document
level. This also means that technically, all your events go through one capture + bubbling loop before even entering the React-specific code. I would not be able to say what that implies performance wise, because you do "lose" the time associated to that first DOM traversal, but on the other hand you will do all your changes in the virtual DOM, which is faster than doing them in the real DOM...
Finally, SyntheticEvent
is indeed a wrapper, which aims at reducing cross-browser compatibility issues. It also introduces pooling, which makes the thing faster by reducing garbage collection time. Besides, as one native event can generate several SyntheticEvent
, it technically lets you create new ones easily (like a syntheticTap
event that could be emitted if you receive a native touchStart
then a native touchEnd
in succession).
I have written a post with more details here. It is far from perfect and their might be some imprecision, but it can perhaps give you some more info on the topic.
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