How Events Work in React | Lecture 134 | React.JS 🔥

The Coding Classroom
6 Dec 202313:42

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

00:00

🌐 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.

05:01

🔍 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.

10:03

🛠 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 propagation refers to the way events travel through the DOM tree from the root to the target element (capturing phase) and then back up to the root (bubbling phase). In the context of the video, it's crucial for understanding how React and browsers handle events. The script uses the example of clicking a button to illustrate how an event travels down to the target element and then bubbles back up, emphasizing the importance of this process in both native JavaScript and React event handling.

💡Event Delegation

Event delegation is a technique where a single event listener is attached to a parent element rather than individual child elements. It leverages the event bubbling phase to handle events on multiple elements. The video script discusses event delegation to explain how it can optimize performance and memory usage in applications, particularly in React, by handling events for many elements with a single handler in a common parent element.

💡DOM Tree

The DOM tree is a hierarchical representation of the document's structure, where each node is an object representing a part of the document. The video emphasizes understanding the DOM tree to grasp how events propagate and are delegated in web applications. It distinguishes between the DOM tree and React's component or fiber tree, highlighting that event propagation concerns the actual structure of the DOM.

💡Synthetic Events

Synthetic events in React are wrappers around the browser's native event system. They provide a consistent interface across different browsers, fixing browser-specific inconsistencies. The script discusses synthetic events to explain how React abstracts native event handling, providing developers with a unified and cross-browser compatible event system.

💡stopPropagation

The stopPropagation method is used to prevent an event from bubbling up the DOM tree. The video script mentions this method to explain how developers can control event propagation in both vanilla JavaScript and React, using it to stop an event from triggering handlers on parent elements.

💡preventDefault

preventDefault is a method used to stop the browser's default action that normally would occur in response to a specific event. The script highlights its importance in React event handling, noting that in React, developers must explicitly call preventDefault on the synthetic event object to prevent default behavior.

💡onClick

onClick is an event handler prop in React used to listen for click events on elements. The video uses this prop as an example to demonstrate how to attach event handlers to elements in React applications, contrasting it with the lowercase onclick attribute in vanilla HTML and the addEventListener method in JavaScript.

💡Root Container

The root container in a React application is the DOM element where the React app is rendered. The video explains that React registers event handlers at this root level, rather than on individual elements, utilizing event delegation internally to handle events efficiently and performantly across the app.

💡Fiber Tree

The fiber tree is an internal structure used by React for rendering and updating the DOM. The script mentions the fiber tree in the context of event handling to illustrate that React attaches event handlers at the root of the fiber tree during the render phase, showcasing an optimization technique that underlies React's event system.

💡onClickCapture

onClickCapture is a prop in React that attaches an event handler during the capturing phase, rather than the bubbling phase. The video script introduces this concept to explain advanced event handling in React, allowing developers to control the phase during which their event handler is executed.

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

play00:01

‫Let's now leave the topics of rendering and state,

play00:04

‫and turn towards another essential part

play00:06

‫of React applications that we haven't

play00:09

‫really talked about yet, and that's events.

play00:13

‫So in this lecture, we will learn how React handles events,

play00:17

‫and how they work behind the scenes,

play00:20

‫but let's start with a quick refresher

play00:23

‫on how event propagation and event delegation

play00:26

‫work in the DOM,

play00:28

‫because this is important to understand how React works,

play00:32

‫and also, because I believe that many people

play00:35

‫don't have a good grasp on how events

play00:37

‫actually work in the browser.

play00:40

‫So let's consider this tree of DOM elements,

play00:44

‫and note that this really is a DOM tree,

play00:47

‫so not a fiber tree or a React element tree.

play00:51

‫And now, let's say that some event happens,

play00:54

‫like a click on one of the three buttons,

play00:57

‫and so here is what's gonna happen in the browser.

play01:00

‫As soon as the event fires,

play01:02

‫a new event object will be created,

play01:05

‫but it will not be created where the click

play01:08

‫actually happened.

play01:09

‫Instead, the object will be created

play01:12

‫at the root of the document,

play01:14

‫so at the very top of the tree.

play01:17

‫From there, the event will then travel down the entire tree

play01:22

‫during the so-called capturing phase,

play01:24

‫all the way, until it reaches the target element,

play01:28

‫and the target element is simply the element

play01:31

‫on which the event was actually first triggered.

play01:35

‫So at the target, we can choose to handle the event

play01:38

‫by placing an event handler function on that element,

play01:42

‫which usually is exactly what we do.

play01:45

‫Then immediately after the target element has been reached,

play01:49

‫the event object travels all the way back up the entire tree

play01:54

‫during the so-called bubbling phase.

play01:57

‫Now, there are two very important things

play01:59

‫to understand about this process.

play02:02

‫The first is that during the capturing and bubbling phase,

play02:06

‫the event really goes through every single child

play02:09

‫and parent element one by one.

play02:12

‫In fact, it's if the event originated

play02:15

‫or happened in each of these DOM elements.

play02:19

‫The second important thing is that by default,

play02:23

‫event handlers listen to events

play02:25

‫not only on the target element,

play02:27

‫but also during the bubbling phase,

play02:30

‫so if we put these two things together,

play02:33

‫it means that every single event handler in a parent element

play02:37

‫will also be executed during the bubbling phase

play02:41

‫as long as it's also listening for the same type of event.

play02:46

‫For example, if we edit another click event handler

play02:49

‫to the header element,

play02:51

‫then during this whole process,

play02:53

‫both the handlers at the target and the header element

play02:57

‫would be executed when the click happens.

play03:00

‫Now, sometimes we actually don't want this behavior,

play03:03

‫and so in that case, we can prevent the event

play03:06

‫from bubbling up any further simply by calling

play03:09

‫the stopPropagation method on the event object,

play03:13

‫and this works in vanilla JavaScript, and also in React,

play03:18

‫but it's actually very rarely necessary,

play03:20

‫so only use this if there really is no other solution.

play03:25

‫Okay, so this is essentially how events work in the browser.

play03:31

‫Now, the fact that events bubble like this

play03:34

‫allows developers to implement a very common

play03:37

‫and very useful technique called event delegation.

play03:41

‫So with event delegation, we can handle events

play03:45

‫for multiple elements in one central place,

play03:48

‫which is one of the parent elements.

play03:51

‫So imagine that instead of three buttons,

play03:54

‫there would be like, 1,000 buttons.

play03:57

‫Now, if we wanted to handle events on all of them,

play04:01

‫each button would have to have its own copy

play04:04

‫of the event handler function,

play04:06

‫which could become problematic

play04:08

‫for the app's performance and memory usage.

play04:11

‫So instead, by using event delegation,

play04:15

‫we can simply add just one handler function

play04:18

‫to the first parent element of these buttons.

play04:22

‫Then when a click happens on one of the buttons,

play04:25

‫the event will bubble up to the options div in this example

play04:29

‫where we can then use the events target property

play04:33

‫in order to check whether the event originated

play04:36

‫from one of the buttons or not,

play04:39

‫and if it did, we can then handle the event

play04:42

‫in this central event handler function.

play04:45

‫Now, if you took my JavaScript course,

play04:47

‫then you will already know how to do this in practice,

play04:50

‫because in fact, we do this all the time

play04:54

‫in vanilla JavaScript applications.

play04:56

‫However, in React apps, it's actually not so common

play05:00

‫for us to use this technique,

play05:03

‫but that might leave you wondering,

play05:05

‫if this is actually not important in React,

play05:08

‫then why are we even talking about this?

play05:11

‫Well, for two reasons.

play05:13

‫First, because sometimes you find some strange behaviors

play05:17

‫related to events in your applications,

play05:20

‫which might actually have to do with event bubbling,

play05:24

‫and so as a good React developer,

play05:27

‫you always want to understand exactly what's going on

play05:30

‫in order to fix these problems,

play05:33

‫and the second reason is that this is actually

play05:37

‫what React does behind the scenes with our events,

play05:41

‫and so let's take a look at that.

play05:44

‫So let's consider this same DOM tree,

play05:48

‫and let's say again that we want to attach

play05:50

‫an event handler to one of the buttons,

play05:53

‫or even to some other DOM element,

play05:56

‫and this is what that would look like in React code.

play06:00

‫So we would simply use the onClick prop

play06:03

‫to listen for click events, and then pass it a function.

play06:07

‫So that's really easy, right?

play06:10

‫Now, if we think about how React

play06:12

‫actually registers these event handlers behind the scenes,

play06:16

‫we might believe that it would look something like this.

play06:21

‫So React might select a button,

play06:23

‫and then add the event handler to that element,

play06:27

‫so that sounds pretty logical, right?

play06:30

‫However, this is actually not what React does internally.

play06:35

‫Instead, what React actually does is to register this

play06:39

‫and all other event handler functions

play06:42

‫to the root DOM container,

play06:44

‫and that root container is simply the DOM element

play06:48

‫in which the React app is displayed.

play06:51

‫So if we use the default of Create React App,

play06:55

‫that's usually the div element with an ID set to route.

play07:00

‫So again, instead of selecting the button

play07:03

‫where we actually placed our event handler,

play07:06

‫we can imagine that React selects the route element,

play07:10

‫and then adds all our event handlers to that element,

play07:15

‫and I say imagine, because the way React

play07:18

‫does all this behind the scenes is actually

play07:21

‫a lot more complex than this,

play07:23

‫but that's not really worth diving into here.

play07:26

‫The only thing that's worth knowing

play07:28

‫is that React physically registers

play07:31

‫one event handler function per event type,

play07:35

‫and it does so at the root note of the fiber tree

play07:38

‫during the render phase.

play07:40

‫So if we have multiple onClick handlers in our code,

play07:45

‫React we'll actually somehow bundle them all together

play07:48

‫and just add one big onClick handler

play07:51

‫to the root node of the fiber tree,

play07:54

‫and so this is yet another important function

play07:57

‫of the fiber tree,

play07:59

‫but anyway, what this means is that behind the scenes,

play08:04

‫React actually performs event delegation

play08:06

‫for all events in our applications.

play08:10

‫So we can say that React delegates all events

play08:13

‫to the root DOM container,

play08:15

‫because that's where they will actually get handled,

play08:19

‫not in the place where we thought we registered them,

play08:23

‫and so this works exactly how we just learned

play08:26

‫in the previous slide.

play08:28

‫So again, whenever a click happens on the button,

play08:32

‫a new event object is fired off,

play08:35

‫which will then travel down the DOM tree

play08:38

‫until it reaches the target element.

play08:41

‫From there, the event will bubble back up.

play08:44

‫Then as soon as the event reaches the root container

play08:48

‫where React registered all our handlers,

play08:51

‫the event will actually finally get handled

play08:54

‫according to whatever handlers match the event

play08:57

‫and the target element.

play08:59

‫And finally, once that's all done,

play09:02

‫the event, of course, continues bubbling up

play09:05

‫until it disappears into nowhere,

play09:08

‫and the beauty of this is that it all happens automatically

play09:12

‫and invisibly just to make our React apps

play09:15

‫yet a little bit more performant.

play09:18

‫Now, just one small detail that I want you to notice

play09:22

‫is that it's really the DOM tree that matters here,

play09:25

‫not the component tree.

play09:27

‫So just because one component is a child

play09:30

‫of another component,

play09:32

‫that doesn't mean that the same is true

play09:35

‫in the displayed DOM tree.

play09:37

‫So just keep that in mind when thinking

play09:39

‫about bubbling in React applications.

play09:44

‫All right, so we talked a lot about events

play09:47

‫and event objects,

play09:48

‫and so now, let's finish by taking a look

play09:51

‫at how these event objects actually work behind the scenes.

play09:56

‫So whenever we declare an event handler like this one,

play10:00

‫React gives us access to the event object

play10:03

‫that was created, just like in vanilla JavaScript.

play10:07

‫However, in React, this event object is actually different.

play10:12

‫So in vanilla JavaScript, we simply get access

play10:16

‫to the native DOM event object, for example,

play10:19

‫pointer event, mouse event, keyboard event, and many others.

play10:25

‫React, on the other hand, will give us something

play10:27

‫called a synthetic event,

play10:30

‫which is basically a thin wrapper

play10:32

‫around the DOM'S native event object,

play10:35

‫and by wrapper we simply mean that synthetic events

play10:39

‫are pretty similar to native event objects,

play10:42

‫but they just add or change some functionalities

play10:46

‫on top of them.

play10:48

‫So these synthetic events have the same interface

play10:52

‫as native event objects,

play10:54

‫and that includes the important methods,

play10:56

‫stopPropagation, and preventDefault.

play11:00

‫What's special about synthetic events though,

play11:03

‫and one of the reasons why the React team

play11:05

‫decided to implement them is the fact

play11:08

‫that they fix some browser inconsistencies,

play11:11

‫making it so that events work in the exact same way

play11:15

‫in all browsers.

play11:16

‫The React team also decided that all

play11:19

‫of the most important synthetic events actually bubble,

play11:23

‫including the focus, blur, and change events,

play11:27

‫which usually do not bubble.

play11:30

‫The only exception here is the scroll event,

play11:32

‫which does also not bubble in React.

play11:36

‫Okay, and now to finish, I want to quickly mention

play11:40

‫some differences between how event handlers work

play11:43

‫in React and vanilla JavaScript.

play11:47

‫The first one is that in React, the prop name

play11:50

‫to attach an event handler are named using camelCase,

play11:54

‫so something like onClick with an upper case C.

play11:58

‫In HTML, on the other hand,

play12:00

‫it would be onclick, all lower case,

play12:03

‫and if we used an addEventListener in vanilla JavaScript,

play12:07

‫the event would simply be called click,

play12:10

‫so without the on prefix.

play12:13

‫Now, in vanilla JavaScript,

play12:15

‫whenever we want to stop the default behavior

play12:18

‫of the browser in response to an event,

play12:20

‫we can return faults from the event handler function,

play12:24

‫and the big example of that is the browser

play12:27

‫automatically reloading the page when we submit a form.

play12:32

‫However, if we would attempt to return faults

play12:35

‫in a React event handler, that would simply not work.

play12:40

‫So in React, the only way to prevent the browser's default

play12:44

‫behavior is to call preventDefault

play12:47

‫on the synthetic event object.

play12:50

‫And finally, in the rare event that you need

play12:52

‫to handle an event in the capturing phase

play12:55

‫rather than in the bubbling phase,

play12:57

‫you can simply attach Capture to the event handler name,

play13:01

‫for example, onClickCapture instead of just onClick,

play13:06

‫but most likely, you will never use this,

play13:09

‫so just keep this somewhere in the back of your mind.

play13:13

‫All right, so what we just learned in this slide

play13:17

‫is basically everything that you need to know in practice

play13:20

‫in order to successfully work with events in React.

play13:25

‫The rest all happens invisibly behind the scenes,

play13:29

‫but I hope that you also found the rest

play13:31

‫of the lecture interesting,

play13:33

‫and that it gave you even more confidence

play13:35

‫in working with events in your applications.

Rate This

5.0 / 5 (0 votes)

Related Tags
ReactWeb DevelopmentEvent HandlingDOMEvent PropagationEvent DelegationJavaScriptProgrammingUI DesignFrontend