Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
React Key Concepts

You're reading from   React Key Concepts Consolidate your knowledge of React's core features

Arrow left icon
Product type Paperback
Published in Dec 2022
Publisher Packt
ISBN-13 9781803234502
Length 590 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Maximilian Schwarzmüller Maximilian Schwarzmüller
Author Profile Icon Maximilian Schwarzmüller
Maximilian Schwarzmüller
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface
1. React – What and Why FREE CHAPTER 2. Understanding React Components and JSX 3. Components and Props 4. Working with Events and State 5. Rendering Lists and Conditional Content 6. Styling React Apps 7. Portals and Refs 8. Handling Side Effects 9. Behind the Scenes of React and Optimization Opportunities 10. Working with Complex State 11. Building Custom React Hooks 12. Multipage Apps with React Router 13. Managing Data with React Router 14. Next Steps and Further Resources Appendix

The Problem with "Vanilla JavaScript"

Vanilla JavaScript is a term commonly used in web development for referring to "JavaScript without any frameworks or libraries". That means, you write all the JavaScript on your own, without falling back to any libraries or frameworks that would provide extra utility functionalities. When working with vanilla JavaScript, you especially don't use major frontend frameworks or libraries like React or Angular.

Using vanilla JavaScript generally has the advantage, that visitors of a website have to download less JavaScript code (as major frameworks and libraries typically are quite sizeable and can quickly add 50+ kb of extra JavaScript code that has to be downloaded).

The downside of relying on vanilla JavaScript is, that you, as the developer, must implement all functionalities from the ground up on your own. This can be error-prone and highly time consuming. Therefore, especially more complex user interfaces and websites can quickly become very hard to manage with vanilla JavaScript.

React simplifies the creation and management of such user interfaces by moving from an imperative to a declarative approach. Though this is a nice sentence, it can be hard to grasp if you haven't worked with React or similar frameworks before. To understand it and the idea behind "imperative vs declarative approaches" and why you might want to use React instead of just vanilla JavaScript, it's helpful to take a step back and evaluate how vanilla JavaScript works.

Here's a short code snippet that shows how you could handle the following user interface actions with vanilla JavaScript:

  1. Add an event listener to a button to listen for click events.
  2. Replace the text of a paragraph with new text once a click on the button occurs.
    const buttonElement = document.querySelector('button');
    const paragraphElement = document.querySelector('p');
    function updateTextHandler() {
      paragraphElement.textContent = 'Text was changed!';
    }
    buttonElement.addEventListener('click', updateTextHandler);

This example is deliberately kept simple, so it's probably not looking too bad or overwhelming. It's just a basic example to show how code is generally written with vanilla JavaScript (a more complex example will be discussed below). But even though this example is very straightforward and easy to digest, working with vanilla JavaScript will quickly reach its limits for feature-rich user interfaces and the code to handle various user interactions therefore also becomes more complex. Code can quickly grow significantly, and therefore maintaining it can become a challenge.

In the preceding example, code is written with vanilla JavaScript and, therefore, imperatively. This means that you write instruction after instruction, and you describe every step that needs to be taken in detail.

The code shown above could be translated to these more human-readable instructions:

  1. Look for an HTML element of type button to obtain a reference to the first button on the page.
  2. Create a constant (i.e., a data container) named buttonElement that holds that button reference.
  3. Repeat step 1 but get a reference to the first element that is of type of p.
  4. Store the paragraph element reference in a constant named paragraphElement.
  5. Add an event listener to the buttonElement that listens for click events and triggers the updateTextHandler function whenever such a click event occurs.
  6. Inside the updateTextHandler function, use the paragraphElement to set its textContent to "Text was changed!".

Do you see how every step that needs to be taken is clearly defined and written out in the code?

This shouldn't be too surprising because that is how most programming languages work: you define a series of steps that must be executed in order. It's an approach that makes a lot of sense because the order of code execution shouldn't be random or unpredictable.

But when working with user interfaces, this imperative approach is not ideal. Indeed, it can quickly become cumbersome because, as a developer, you have to add a lot of instructions that despite adding little value, cannot simply be omitted. You need to write all the DOM (Document Object Model) instructions that allow your code to interact with elements, add elements, manipulate elements. etc.

Your core business logic (e.g., deriving and defining the actual text that should be set after a click) therefore often makes up only a small chunk of the overall code. When controlling and manipulating web user interfaces with JavaScript, a huge chunk (often the majority) of your code is frequently made up of DOM instructions, event listeners, HTML element operations, and UI state management.

Therefore, you end up describing all the steps that are required to interact with the UI technically and all the steps that are required to derive the output data (i.e., the desired final state of the UI).

Note

This book assumes that you are familiar with the DOM (Document Object Model). In a nutshell, the DOM is the "bridge" between your JavaScript code and the HTML code of the website with which you want to interact. Via the built-in DOM API, JavaScript is able to create, insert, manipulate, delete, and read HTML elements and their content.

You can learn more about the DOM in this article: https://academind.com/tutorials/what-is-the-dom.

Modern web user interfaces are often quite complex, with lots of interactivity going on behind the scenes. Your website might need to listen for user input in an input field, send that entered data to a server to validate it, output a validation feedback message on the screen, and show an error overlay modal if incorrect data is submitted.

This is not a complex example in general, but the vanilla JavaScript code for implementing such a scenario can be overwhelming. You end up with lots of DOM selection, insertion, and manipulation operations, as well as multiple lines of code that do nothing but manage event listeners. And keeping the DOM updated, without introducing bugs or errors, can be a nightmare since you must ensure that you update the right DOM element with the right value at the right time. Below, you will find a screenshot of some example code for the described use-case.

Note

The full, working, code can be found on GitHub at https://packt.link/tLSLU.

If you take a look at the JavaScript code in the screenshot (or in the linked repository), you will probably be able to imagine how a more complex user interface is likely to look.

Figure 1.1. An example JavaScript code file that contains over 100 lines 
of code for a fairly trivial user interface

Figure 1.1. An example JavaScript code file that contains over 100 lines of code for a fairly trivial user interface

This example JavaScript file already contains roughly 110 lines of code. Even after minifying ("minifying" means that code is shortened automatically, e.g. by replacing long variable names with shorter ones and removing redundant whitespace; in this case via https://javascript-minifier.com/) it and splitting the code across multiple lines thereafter (to count the raw lines of code), it still has around 80 lines of code. That's a full 80 lines of code for a simple user interface with only basic functionality. The actual business logic (i.e., input validation, determining if and when overlays should be shown, and defining the output text) only makes up a small fraction of the overall codebase—around 20 to 30 lines of code, in this case (around 20 after minifying).

That's roughly 75% of code spent on pure DOM interaction, DOM state management, and similar boilerplate tasks.

As you can see by these examples and numbers, controlling all the UI elements and their different states (e.g., whether an info box is visible or not) is a challenging task and trying to create such interfaces with just JavaScript often leads to complex code that might even contain errors.

That's why the imperative approach, wherein you must define and write down every single step, has its limits in situations like this. This is the reason why React provides utility functionalities that allow you to write code differently: with a declarative approach.

Note

This is not a scientific paper, and the preceding example is not meant to act as an exact scientific study. Depending on how you count lines and which kind of code you consider to be "core business logic", you will end up with higher or lower percentage values. The key message doesn't change though: Lots of code (in this case most of it) deals with the DOM and DOM manipulation—not with the actual logic that defines your website and its key features.

You have been reading a chapter from
React Key Concepts
Published in: Dec 2022
Publisher: Packt
ISBN-13: 9781803234502
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.
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 $19.99/month. Cancel anytime
Banner background image