Understanding React Synthetic Event System

It was in my opinion for several days.

According to the docs, React has a synthesized event system , which is a cross-browser wrapper around the browser native event . Looking through the documents, I understand that the usual (synthetic) event system is not efficiency, but compatibility with several browsers.

In other words, is React still adding an event to the element, rather than a more efficient approach for delegating events in the parent element?

I also noticed this in the Firefox Inspector, which raised initial curiosity.

The reason the question is asked is because I’m working on an application where the user can select a thousand elements and drag them around the screen, so event delegation will eventually happen.

+5
source share
1 answer

Well, you may have already sorted it all out yourself, but when I asked myself the same questions, I decided that I would leave it here if someone is more interested in not only using React, but also getting an idea of ​​how this works.

So, I'm not quite sure about your question (especially the “adding an event to an element” part), but:

  • Reacts to a virtual DOM. As the name implies, it is built on top of the "real" environment, which is the DOM. Therefore, everything happens in this abstracted layer , including event handling.
  • Events appear in their "natural" environment, so DOM or native (depending on what effect you use)

Therefore, first you need to bring the events to the virtual DOM, compute your changes there and send them to the component view in the virtual DOM, and then bring the corresponding changes back so that they are reflected in the DOM accordingly.

Changes are transferred to the virtual DOM using top-level delegation . This means that React itself listens for all events at the document level. It also means that technically all your events go through one capture + bubble cycle , even if it enters React-specific code . I would not be able to say what performance implies, because you are "wasting" the time associated with this first DOM bypass, but on the other hand, you will make all your changes in the virtual DOM, which is faster than making them in the real DOM ...

Finally, SyntheticEvent indeed a wrapper whose goal is to reduce browser compatibility issues. It also introduces pooling, which speeds up work by reducing garbage collection time. In addition, since multiple SyntheticEvent events can generate one event of its own, it technically makes it easy to create new events (for example, a syntheticTap event, which can be touchStart if you get your own touchStart , and then a native touchEnd in a row).

I wrote a post with more details here . This is far from ideal, and there may be some inaccuracy, but it may give you additional information on this topic.

0
source

Source: https://habr.com/ru/post/1264416/


All Articles