Reader small image

You're reading from  React and React Native - Fifth Edition

Product typeBook
Published inApr 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781805127307
Edition5th Edition
Languages
Tools
Right arrow
Authors (2):
Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

View More author details
Right arrow

Event Handling in the React Way

The focus of this chapter is event handling. React has a unique approach to handling events: declaring event handlers in JSX. We’ll get things started by looking at how event handlers for particular elements are declared in JSX. Then, we’ll explore inline and higher-order event handler functions.

Afterward, you’ll learn how React maps event handlers to DOM elements under the hood. Finally, you’ll learn about the synthetic events that React passes to event handler functions and how they’re pooled for performance purposes. Once you’ve completed this chapter, you’ll be comfortable implementing event handlers in your React components. At that point, your applications come to life for your users because they are then able to interact with them.

The following topics are covered in this chapter:

  • Declaring event handlers
  • Declaring inline event handlers
  • Binding handlers to elements...

Technical requirements

The code presented in this chapter can be found at the following link: https://github.com/PacktPublishing/React-and-React-Native-5E/tree/main/Chapter04

Declaring event handlers

The differentiating factor with event handling in React components is that it’s declarative. Compare this with something such as jQuery, where you have to write imperative code that selects the relevant DOM elements and attaches event handler functions to them.

The advantage of the declarative approach to event handlers in JSX markup is that they’re part of the UI structure. Not having to track down code that assigns event handlers is mentally liberating.

In this section, you’ll write a basic event handler so that you can get a feel for the declarative event handling syntax found in React applications. Then, you’ll learn how to use generic event handler functions.

Declaring handler functions

Let’s take a look at a basic component that declares an event handler for the click event of an element:

function MyButton(props) {
  const clickHandler = () => {
    console.log("clicked");
  };
  return...

Declaring inline event handlers

The typical approach to assigning handler functions to JSX properties is to use a named function. However, sometimes, you might want to use an inline function, where the function is defined as part of the markup. This is done by assigning an arrow function directly to the event property in the JSX markup:

function MyButton(props) {
  return (
    <button onClick={(e) => console.log("clicked", e)}>
      {props.children}
    </button>
  );
}

The main use of inlining event handlers like this is when you have a static parameter value that you want to pass to another function. In this example, you’re calling console.log with the clicked string. You could have set up a special function for this purpose outside of the JSX markup by creating a new function or by using a higher-order function. But then you would have to think of yet another name for yet another function. Inlining is just easier sometimes.

Next, you...

Binding handlers to elements

When you assign an event handler function to an element in JSX, React doesn’t actually attach an event listener to the underlying DOM element. Instead, it adds the function to an internal mapping of functions. There’s a single event listener on the document for the page. As events bubble up through the DOM tree to the document, the React handler checks to see whether any components have matching handlers. The process is illustrated here:

Figure 4.1: The event handler cycle

Why does React go through all of this trouble, you might ask? It’s the same principle that I’ve been covering in the last few chapters: keep the declarative UI structures separated from the DOM as much as possible. The DOM is merely a render target; React’s architecture allows it to remain agnostic about the final rendering destination and event system.

For example, when a new component is rendered, its event handler functions are simply...

Using synthetic event objects

When you attach an event handler function to a DOM element using the native addEventListener function, the callback will get an event argument passed to it. Event handler functions in React are also passed an event argument but it’s not the standard event instance. It’s called SyntheticEvent and it’s a simple wrapper for native event instances.

Synthetic events serve two purposes in React:

  • They provide a consistent event interface, normalizing browser inconsistencies.
  • They contain information that’s necessary for propagation to work.

Here’s a diagram of the synthetic event in the context of a React component:

Figure 4.2: How synthetic events are created and processed

When a DOM element that is part of a React component dispatches an event, React will handle the event because it sets up its own listeners for them. Then, it will either create a new synthetic event or reuse one...

Understanding event pooling

One challenge of wrapping native event instances is that it can cause performance issues. Every synthetic event wrapper that’s created will also need to be garbage collected at some point, which can be expensive in terms of CPU time.

When the garbage collector is running, none of your JavaScript code is able to run. This is why it’s important to be memory-efficient; frequent garbage collection means less CPU time for code that responds to user interactions.

For example, if your application only handles a few events, this wouldn’t matter much. But even by modest standards, applications respond to many events, even if the handlers don’t actually do anything with them. This is problematic if React constantly has to allocate new synthetic event instances.

React deals with this problem by allocating a synthetic instance pool. Whenever an event is triggered, it takes an instance from the pool and populates its...

Summary

This chapter introduced you to event handling in React. The key differentiator between React and other approaches to event handling is that handlers are declared in JSX markup. This makes tracking down which elements handle which events much simpler.

You learned that having multiple event handlers on a single element is a matter of adding new JSX properties. Then, you learned about inline event handler functions and their potential use, as well as how React actually binds a single DOM event handler to the document object.

Synthetic events are abstractions that wrap native events; you learned why they’re necessary and how they’re pooled for efficient memory consumption.

In the next chapter, you’ll learn how to create components that are reusable for a variety of purposes. Instead of writing new components for each use case that you encounter, you’ll learn the skills necessary to refactor existing components so that they can be used in...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127307
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Authors (2)

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch