How Events Work in React | Lecture 134 | React.JS đ„
Summary
TLDRThis lecture delves into how React handles events and their underlying mechanisms, starting with a primer on event propagation and delegation in the DOM to lay the groundwork for understanding React's approach. It explains the process of events bubbling through the DOM tree and introduces the concept of event delegation for efficient event handling across multiple elements. The discussion transitions to React's unique handling of events, highlighting the use of synthetic events to normalize browser inconsistencies and the practice of attaching event handlers to the root container for performance gains. The lecture concludes by contrasting event handling in React with vanilla JavaScript, emphasizing differences in syntax, event object handling, and phase capturing.
Takeaways
- đŁ Events in the browser follow a propagation pattern: capturing phase (top to target) and bubbling phase (target to top).
- đŻ By default, event handlers listen to events during the bubbling phase, allowing parent elements to handle child events.
- 𧩠Event delegation allows handling events for multiple elements in one central place, improving performance and memory usage.
- đ In React, event handlers are registered to the root DOM container, not individual elements, utilizing event delegation behind the scenes.
- ⥠React creates a synthetic event object, a wrapper around the native DOM event, to fix browser inconsistencies and ensure consistent event behavior.
- đ React bubbles focus, blur, and change events, which normally don't bubble, except for the scroll event.
- đ« React uses camelCase for event handler prop names (e.g., onClick), unlike vanilla JavaScript (onclick or click).
- đ« To prevent default browser behavior in React, use event.preventDefault(), as returning false from the handler doesn't work.
- đ Attach 'Capture' to the event handler name (e.g., onClickCapture) to handle events in the capturing phase, though rarely used.
- đ§ Understanding event propagation and React's event handling mechanisms helps diagnose and fix strange event-related behaviors in applications.
Q & A
What is event propagation in the context of the DOM?
-Event propagation is the process by which an event travels through the DOM tree. It starts at the root of the document, goes down to the target element during the capturing phase, and then bubbles back up to the root during the bubbling phase.
How does event delegation work in the DOM and why is it useful?
-Event delegation is a technique where event listeners are added to a parent element instead of individual child elements. It's useful for handling events on multiple elements in one central place, improving app performance and memory usage, especially with a large number of elements.
How does React handle events differently from vanilla JavaScript?
-React handles events by registering all event handler functions to the root DOM container of the React app instead of directly on the target element. This approach allows React to perform event delegation automatically for all events in applications.
What is the significance of the capturing and bubbling phases in event propagation?
-The capturing and bubbling phases are important for understanding how events travel through the DOM tree. The capturing phase is when the event travels down to the target element, and the bubbling phase is when it travels back up. This process allows for more flexible event handling strategies.
Why might you want to prevent an event from bubbling in a React application?
-Preventing an event from bubbling can be necessary to stop the event from being handled by parent elements' event handlers when such behavior is not desired. It's done by calling the stopPropagation method on the event object, although it's rarely necessary.
What are synthetic events in React and why are they used?
-Synthetic events in React are wrappers around the browser's native event objects. They provide a consistent interface across different browsers, fixing browser inconsistencies and including some additional functionalities. This makes event handling in React more reliable and consistent.
How does React's event handling improve app performance?
-React's event handling improves app performance by using event delegation at the root DOM container. This means React only needs to register one event handler per event type, reducing the number of event listeners and simplifying event management across the application.
In React, how can you stop the default behavior triggered by an event?
-In React, to stop the default behavior triggered by an event, you must call the preventDefault method on the synthetic event object. Returning false from an event handler function, as you might in vanilla JavaScript, does not work.
What is the difference between the way event handlers are named in React and in vanilla JavaScript?
-In React, event handler props are named using camelCase, like onClick, while in HTML it would be all lowercase (onclick), and in vanilla JavaScript addEventListener method, the event is referred to simply by its type, like 'click', without the 'on' prefix.
How can you handle an event in the capturing phase instead of the bubbling phase in React?
-In React, to handle an event in the capturing phase, you can attach 'Capture' to the event handler name, for example, using onClickCapture instead of just onClick. This allows you to catch events in the capturing phase rather than the default bubbling phase.
Outlines
đ Understanding Events in React
This section transitions from the topics of rendering and state management in React to focus on event handling, which is crucial yet less discussed. It begins with a refresher on how event propagation and delegation work in the traditional Document Object Model (DOM), illustrating the process of event capturing and bubbling. The narrative then moves to explain the significance of understanding these concepts for React developers, given that many might not be fully aware of how events operate in a browser context. The example of clicking a button within a DOM tree is used to elucidate how events originate, propagate, and can be managed through event handlers and the stopPropagation method, both in vanilla JavaScript and React.
đ React's Event Handling Mechanism
This part delves into the nuances of handling events in React applications, raising the question of why understanding traditional event delegation is necessary when React seems to abstract these details away. It explains React's approach to event handling, which involves attaching event handlers not to the individual elements but to the root DOM container of the React application. This section highlights how React internally employs event delegation for performance optimization by bundling multiple event handlers and attaching them to the root of the fiber tree. It emphasizes the automatic and invisible nature of this process, which enhances application performance without the developer's active intervention. The discussion underscores the distinction between the component tree and the DOM tree in React, advising developers to consider the latter when thinking about event propagation.
đ React's Synthetic Events and Differences from Vanilla JavaScript
The final segment introduces React's synthetic events, which are wrappers around native DOM event objects designed to normalize browser inconsistencies and extend functionalities. It outlines the characteristics of synthetic events, including their interface and methods like stopPropagation and preventDefault, and notes the exception of certain events that do not bubble in React, such as the scroll event. The narrative contrasts event handling in React with vanilla JavaScript, covering differences in naming conventions, the inability to use return false to prevent default actions in React, and the provision for handling events during the capturing phase. The summary encapsulates the practical knowledge necessary for working with events in React and reassures developers of the underlying complexities being managed by React behind the scenes.
Mindmap
Keywords
đĄEvent Propagation
đĄEvent Delegation
đĄDOM Tree
đĄSynthetic Events
đĄstopPropagation
đĄpreventDefault
đĄonClick
đĄRoot Container
đĄFiber Tree
đĄonClickCapture
Highlights
React handles events behind the scenes by delegating them to the root DOM container, rather than registering event handlers directly on the target elements.
Event propagation and event delegation in the DOM are essential concepts for understanding how React handles events.
During event propagation, events travel down the DOM tree (capturing phase), reach the target element, and then travel back up (bubbling phase).
By default, event handlers in React listen to events during the bubbling phase.
Event delegation allows handling events for multiple elements in one central place, improving performance and memory usage.
React physically registers one event handler function per event type at the root node of the fiber tree during the render phase.
React's synthetic events are wrappers around the DOM's native event objects, fixing browser inconsistencies and ensuring events work the same way across browsers.
Important synthetic event methods, like stopPropagation and preventDefault, have the same interface as native event objects.
In React, event handler props are named using camelCase (e.g., onClick), while in HTML and vanilla JavaScript, they are named differently (onclick, click).
To prevent the browser's default behavior in React, you must call preventDefault on the synthetic event object, rather than returning false from the event handler.
React provides the option to attach event handlers for the capturing phase by adding 'Capture' to the event handler name (e.g., onClickCapture).
Understanding event bubbling and delegation in React can help diagnose and fix strange behaviors related to events in applications.
React's event handling mechanism is designed to make applications more performant by leveraging event delegation and synthetic events.
The DOM tree, not the component tree, is crucial for understanding event bubbling in React applications.
Mastering event handling in React provides confidence and proficiency in working with events in applications.
Transcripts
â«Let's now leave the topics of rendering and state,
â«and turn towards another essential part
â«of React applications that we haven't
â«really talked about yet, and that's events.
â«So in this lecture, we will learn how React handles events,
â«and how they work behind the scenes,
â«but let's start with a quick refresher
â«on how event propagation and event delegation
â«work in the DOM,
â«because this is important to understand how React works,
â«and also, because I believe that many people
â«don't have a good grasp on how events
â«actually work in the browser.
â«So let's consider this tree of DOM elements,
â«and note that this really is a DOM tree,
â«so not a fiber tree or a React element tree.
â«And now, let's say that some event happens,
â«like a click on one of the three buttons,
â«and so here is what's gonna happen in the browser.
â«As soon as the event fires,
â«a new event object will be created,
â«but it will not be created where the click
â«actually happened.
â«Instead, the object will be created
â«at the root of the document,
â«so at the very top of the tree.
â«From there, the event will then travel down the entire tree
â«during the so-called capturing phase,
â«all the way, until it reaches the target element,
â«and the target element is simply the element
â«on which the event was actually first triggered.
â«So at the target, we can choose to handle the event
â«by placing an event handler function on that element,
â«which usually is exactly what we do.
â«Then immediately after the target element has been reached,
â«the event object travels all the way back up the entire tree
â«during the so-called bubbling phase.
â«Now, there are two very important things
â«to understand about this process.
â«The first is that during the capturing and bubbling phase,
â«the event really goes through every single child
â«and parent element one by one.
â«In fact, it's if the event originated
â«or happened in each of these DOM elements.
â«The second important thing is that by default,
â«event handlers listen to events
â«not only on the target element,
â«but also during the bubbling phase,
â«so if we put these two things together,
â«it means that every single event handler in a parent element
â«will also be executed during the bubbling phase
â«as long as it's also listening for the same type of event.
â«For example, if we edit another click event handler
â«to the header element,
â«then during this whole process,
â«both the handlers at the target and the header element
â«would be executed when the click happens.
â«Now, sometimes we actually don't want this behavior,
â«and so in that case, we can prevent the event
â«from bubbling up any further simply by calling
â«the stopPropagation method on the event object,
â«and this works in vanilla JavaScript, and also in React,
â«but it's actually very rarely necessary,
â«so only use this if there really is no other solution.
â«Okay, so this is essentially how events work in the browser.
â«Now, the fact that events bubble like this
â«allows developers to implement a very common
â«and very useful technique called event delegation.
â«So with event delegation, we can handle events
â«for multiple elements in one central place,
â«which is one of the parent elements.
â«So imagine that instead of three buttons,
â«there would be like, 1,000 buttons.
â«Now, if we wanted to handle events on all of them,
â«each button would have to have its own copy
â«of the event handler function,
â«which could become problematic
â«for the app's performance and memory usage.
â«So instead, by using event delegation,
â«we can simply add just one handler function
â«to the first parent element of these buttons.
â«Then when a click happens on one of the buttons,
â«the event will bubble up to the options div in this example
â«where we can then use the events target property
â«in order to check whether the event originated
â«from one of the buttons or not,
â«and if it did, we can then handle the event
â«in this central event handler function.
â«Now, if you took my JavaScript course,
â«then you will already know how to do this in practice,
â«because in fact, we do this all the time
â«in vanilla JavaScript applications.
â«However, in React apps, it's actually not so common
â«for us to use this technique,
â«but that might leave you wondering,
â«if this is actually not important in React,
â«then why are we even talking about this?
â«Well, for two reasons.
â«First, because sometimes you find some strange behaviors
â«related to events in your applications,
â«which might actually have to do with event bubbling,
â«and so as a good React developer,
â«you always want to understand exactly what's going on
â«in order to fix these problems,
â«and the second reason is that this is actually
â«what React does behind the scenes with our events,
â«and so let's take a look at that.
â«So let's consider this same DOM tree,
â«and let's say again that we want to attach
â«an event handler to one of the buttons,
â«or even to some other DOM element,
â«and this is what that would look like in React code.
â«So we would simply use the onClick prop
â«to listen for click events, and then pass it a function.
â«So that's really easy, right?
â«Now, if we think about how React
â«actually registers these event handlers behind the scenes,
â«we might believe that it would look something like this.
â«So React might select a button,
â«and then add the event handler to that element,
â«so that sounds pretty logical, right?
â«However, this is actually not what React does internally.
â«Instead, what React actually does is to register this
â«and all other event handler functions
â«to the root DOM container,
â«and that root container is simply the DOM element
â«in which the React app is displayed.
â«So if we use the default of Create React App,
â«that's usually the div element with an ID set to route.
â«So again, instead of selecting the button
â«where we actually placed our event handler,
â«we can imagine that React selects the route element,
â«and then adds all our event handlers to that element,
â«and I say imagine, because the way React
â«does all this behind the scenes is actually
â«a lot more complex than this,
â«but that's not really worth diving into here.
â«The only thing that's worth knowing
â«is that React physically registers
â«one event handler function per event type,
â«and it does so at the root note of the fiber tree
â«during the render phase.
â«So if we have multiple onClick handlers in our code,
â«React we'll actually somehow bundle them all together
â«and just add one big onClick handler
â«to the root node of the fiber tree,
â«and so this is yet another important function
â«of the fiber tree,
â«but anyway, what this means is that behind the scenes,
â«React actually performs event delegation
â«for all events in our applications.
â«So we can say that React delegates all events
â«to the root DOM container,
â«because that's where they will actually get handled,
â«not in the place where we thought we registered them,
â«and so this works exactly how we just learned
â«in the previous slide.
â«So again, whenever a click happens on the button,
â«a new event object is fired off,
â«which will then travel down the DOM tree
â«until it reaches the target element.
â«From there, the event will bubble back up.
â«Then as soon as the event reaches the root container
â«where React registered all our handlers,
â«the event will actually finally get handled
â«according to whatever handlers match the event
â«and the target element.
â«And finally, once that's all done,
â«the event, of course, continues bubbling up
â«until it disappears into nowhere,
â«and the beauty of this is that it all happens automatically
â«and invisibly just to make our React apps
â«yet a little bit more performant.
â«Now, just one small detail that I want you to notice
â«is that it's really the DOM tree that matters here,
â«not the component tree.
â«So just because one component is a child
â«of another component,
â«that doesn't mean that the same is true
â«in the displayed DOM tree.
â«So just keep that in mind when thinking
â«about bubbling in React applications.
â«All right, so we talked a lot about events
â«and event objects,
â«and so now, let's finish by taking a look
â«at how these event objects actually work behind the scenes.
â«So whenever we declare an event handler like this one,
â«React gives us access to the event object
â«that was created, just like in vanilla JavaScript.
â«However, in React, this event object is actually different.
â«So in vanilla JavaScript, we simply get access
â«to the native DOM event object, for example,
â«pointer event, mouse event, keyboard event, and many others.
â«React, on the other hand, will give us something
â«called a synthetic event,
â«which is basically a thin wrapper
â«around the DOM'S native event object,
â«and by wrapper we simply mean that synthetic events
â«are pretty similar to native event objects,
â«but they just add or change some functionalities
â«on top of them.
â«So these synthetic events have the same interface
â«as native event objects,
â«and that includes the important methods,
â«stopPropagation, and preventDefault.
â«What's special about synthetic events though,
â«and one of the reasons why the React team
â«decided to implement them is the fact
â«that they fix some browser inconsistencies,
â«making it so that events work in the exact same way
â«in all browsers.
â«The React team also decided that all
â«of the most important synthetic events actually bubble,
â«including the focus, blur, and change events,
â«which usually do not bubble.
â«The only exception here is the scroll event,
â«which does also not bubble in React.
â«Okay, and now to finish, I want to quickly mention
â«some differences between how event handlers work
â«in React and vanilla JavaScript.
â«The first one is that in React, the prop name
â«to attach an event handler are named using camelCase,
â«so something like onClick with an upper case C.
â«In HTML, on the other hand,
â«it would be onclick, all lower case,
â«and if we used an addEventListener in vanilla JavaScript,
â«the event would simply be called click,
â«so without the on prefix.
â«Now, in vanilla JavaScript,
â«whenever we want to stop the default behavior
â«of the browser in response to an event,
â«we can return faults from the event handler function,
â«and the big example of that is the browser
â«automatically reloading the page when we submit a form.
â«However, if we would attempt to return faults
â«in a React event handler, that would simply not work.
â«So in React, the only way to prevent the browser's default
â«behavior is to call preventDefault
â«on the synthetic event object.
â«And finally, in the rare event that you need
â«to handle an event in the capturing phase
â«rather than in the bubbling phase,
â«you can simply attach Capture to the event handler name,
â«for example, onClickCapture instead of just onClick,
â«but most likely, you will never use this,
â«so just keep this somewhere in the back of your mind.
â«All right, so what we just learned in this slide
â«is basically everything that you need to know in practice
â«in order to successfully work with events in React.
â«The rest all happens invisibly behind the scenes,
â«but I hope that you also found the rest
â«of the lecture interesting,
â«and that it gave you even more confidence
â«in working with events in your applications.
Weitere Àhnliche Videos ansehen
![](https://i.ytimg.com/vi/hXjAygMEPIY/hq720.jpg)
Multiple ways of Fetching Events in React #knowledgekeen
![](https://i.ytimg.com/vi/YiOlaiscqDY/hq720.jpg)
A Complete Overview of JavaScript Events - All You Need To Know
![](https://i.ytimg.com/vi/XF1_MlZ5l6M/hq720.jpg)
Learn JavaScript Event Listeners In 18 Minutes
![](https://i.ytimg.com/vi/wIyHSOugGGw/hq720.jpg)
Every React Concept Explained in 12 Minutes
![](https://i.ytimg.com/vi/1H7kmNfp3fo/hq720.jpg)
State Update Batching in Practice | Lecture 133 | React.JS đ„
![](https://i.ytimg.com/vi/cvOj6iwCU1Y/hq720.jpg)
How Rendering Works: The Render Phase | Lecture 124 | React.JS đ„
5.0 / 5 (0 votes)