Home Web Development React Key Concepts

React Key Concepts

By Maximilian Schwarzmüller
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $35.99 $24.99
Print $44.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $35.99 $24.99
Print $44.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    1. React – What and Why
About this book
As the most popular JavaScript library for building modern, interactive user interfaces, React is an in-demand framework that’ll bring real value to your career or next project. But like any technology, learning React can be tricky, and finding the right teacher can make things a whole lot easier. Maximilian Schwarzmüller is a bestselling instructor who has helped over two million students worldwide learn how to code, and his latest React video course (React — The Complete Guide) has over six hundred thousand students on Udemy. Max has written this quick-start reference to help you get to grips with the world of React programming. Simple explanations, relevant examples, and a clear, concise approach make this fast-paced guide the ideal resource for busy developers. This book distills the core concepts of React and draws together its key features with neat summaries, thus perfectly complementing other in-depth teaching resources. So, whether you've just finished Max’s React video course and are looking for a handy reference tool, or you've been using a variety of other learning materials and now need a single study guide to bring everything together, this is the ideal companion to support you through your next React projects. Plus, it's fully up to date for React 18, so you can be sure you’re ready to go with the latest version.
Publication date:
December 2022
Publisher
Packt
Pages
590
ISBN
9781803234502

 

1. React – What and Why

Learning Objectives

By the end of this chapter, you will be able to do the following:

– Describe what React is and why you would use it

– Compare React to web projects built with just JavaScript

– Create new React projects

 

Introduction

React.js (or just React, as it's also called and as it'll be referred to for the majority of this book) is one of the most popular frontend JavaScript libraries—maybe even the most popular one, according to a 2021 Stack Overflow developer survey. It is currently used by over 5% of the top 1,000 websites and compared to other popular frontend JavaScript frameworks like Angular, React is leading by a huge margin, when looking at key metrics like weekly package downloads via npm (Node Package Manager), which is a tool commonly used for downloading and managing JavaScript packages.

Though it is certainly possible to write good React code without fully understanding how React works and why you're using it, you should always aim to understand the tools you're working with as well as the reasons for picking a certain tool in the first place.

Therefore, before considering anything about its core concepts and ideas or reviewing example code, you first need to understand what React actually is and why it exists. This will help you understand how React works internally and why it offers the features it does.

If you already know why you're using React, why solutions like React in general are being used instead of vanilla JavaScript (i.e. JavaScript without any frameworks or libraries, more on this in the next section), and what the idea behind React and its syntax is, you may of course skip this section and jump ahead to the more practice-oriented chapters later in this book.

But if you only think that you know it and are not 100% certain, you should definitely follow along with this chapter first.

 

What Is React?

React is a JavaScript library, and if you take a look at the official webpage (Official React website and documentation: https://reactjs.org), you learn that it's actually a "JavaScript library for building user interfaces".

But what does this mean?

It should be clear what JavaScript is and why you use JavaScript in the browser (React is mostly a browser-side JavaScript library). JavaScript allows you to add interactivity to your website since, with JavaScript, you can react to user events and manipulate the page after it was loaded. This is extremely valuable as it allows you to build highly interactive web user interfaces.

But what is a "library" and how does React help with "building user interfaces"?

While you can have philosophical discussions about what a library is (and how it differs from a framework), the pragmatic definition of a library is that it's a collection of functionalities that you can use in your code to achieve results that would normally require more code and work from your side. Libraries help you write better and shorter code and enable you to implement certain features more quickly. In addition, since you can focus on your "core business logic", you not only move faster but are also likely to produce better code since you don't have to reinvent the wheel for problems that have been solved before by others.

React is such a library—one that focuses on providing functionalities that help you create interactive and reactive user interfaces. Indeed, React deals with more than web interfaces (i.e. websites loaded in browsers). You can also build native mobile devices with React and React Native, which is another library that utilizes React under the hood. No matter which platform you're targeting though, creating interactive user interfaces with just JavaScript can quickly become very complex and overwhelming.

Note

The focus of this book is on React in general, and for simplicity, the focus lies on React for websites. With projects like React Native, you can also use React to build user interfaces for native mobile apps. The React concepts covered in this book still apply, no matter which target platform is chosen. But examples will focus on React for web browsers.

 

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.

 

React and Declarative Code

Coming back to the first, simple, code snippet from above, here's that same code snippet, this time using React:

import { useState } from 'react';
function App() {
  const [outputText, setOutputText] = useState('Initial text');
  function updateTextHandler() {
    setOutputText('Text was changed!');
  }
  return (
    <>
      <button onClick={updateTextHandler}>Click to change text</button>
      <p>{outputText}</p>
    </>
  );
}

This snippet performs the same operations as the first did with just vanilla JavaScript:

  1. Add an event listener to a button to listen for click events (now with some React-specific syntax: onClick={…}).
  2. Replace the text of a paragraph with new text once the click on the button occurred.

Nonetheless, this code looks totally different—like a mixture of JavaScript and HTML. And indeed, React uses a syntax extension called JSX (i.e., JavaScript with embedded XML). For the moment, it's enough to understand that this JSX code will work because of a pre-processing step that's part of the build workflow of every React project.

Pre-processing means that certain tools, which are part of React projects, analyze and transform the code before its deployed. This allows for development-only syntax like JSX which would not work in the browser and is therefore transformed to regular JavaScript before deployment. (You'll get a thorough introduction into JSX in Chapter 2, Understanding React Components and JSX.)

In addition, the snippet shown above contains a React specific feature: State. State will be discussed in greater detail later in the book (Chapter 4, Working with Events and State will focus on handling events and state with React). For the moment, you can think of this state as a variable that, when changed, will trigger React to update the user interface in the browser.

What you see in the preceding example is the "declarative approach" used by React: You write your JavaScript logic (e.g., functions that should eventually be executed), and you combine that logic with the HTML code that should trigger it or that is affected by it. You don't write the instructions for selecting certain DOM elements or changing the text content of some DOM elements. Instead, with React and JSX, you focus on your JavaScript business logic and define the desired HTML output that should eventually be reached. This output can and typically will contain dynamic values that are derived inside of your main JavaScript code.

In the preceding example, outputText is some state managed by React. In the code, the updateTextHandler function is triggered upon a click, and the outputText state value is set to a new string value ('Text was changed!') with help of the setOutputText function. The exact details of what's going on here will be explored in Chapter 4.

The general idea, though, is that the state value is changed and, since it's being referenced in the last paragraph (<p>{outputText}</p>), React outputs the current state value in that place in the actual DOM (and therefore on the actual web page). React will keep the paragraph updated, and therefore, whenever outputText changes, React will select this paragraph element again and update its textContent automatically.

This is the declarative approach in action. As a developer, you don't need to worry about the technical details (for example, selecting the paragraph, updating its textContent). Instead, you will hand this work off to React. You will only need to focus on the desired end state(s) where the goal simply is to output the current value of outputText in a specific place (i.e., in the second paragraph in this case) on the page. It's React's job of doing the "behind the scenes" work of getting to that result.

It turns out that this code snippet isn't shorter than the vanilla JavaScript one; indeed, it's actually even a bit longer. But that's only the case because this first snippet was deliberately kept simple and concise. In such cases, React actually adds a bit of overhead code. If that were your entire user interface, using React indeed wouldn't make too much sense. Again, this snippet was chosen because it allows us to see the differences at a glance. Things change if you take a look at the more complex vanilla JavaScript example from before) and compare that to its React alternative.

Note

Referenced code can be found on GitHub at http://packt.link/tLSLU and https://packt.link/YkpRa, respectively.

Figure 1.2. The code snippet from before, now implemented via React.

Figure 1.2. The code snippet from before, now implemented via React.

It's still not short because all the JSX code (i.e., the HTML output) is included in the JavaScript file. If you ignore pretty much the entire right side of that screenshot (since HTML was not part of the vanilla JavaScript files either), the React code gets much more concise. But, most importantly, if you take a closer look at all the React code (also in the first, shorter snippet), you will notice that there are absolutely no operations that would select DOM elements, create or insert DOM elements, or edit DOM elements.

And this is the core idea of React. You don't write down all the individual steps and instructions; instead, you focus on the "big picture" and the desired end state(s) of your page content. With React, you can merge your JavaScript and markup code without having to deal with the low-level instructions of interacting with the DOM like selecting elements via document.getElementById() or similar operations.

Using this declarative approach, instead of the imperative approach with vanilla JavaScript, allows you, the developer, to focus on your core business logic and the different states of your HTML code. You don't need to define all the individual steps that have to be taken (like "adding an event listener", "selecting a paragraph", etc.), and this simplifies the development of complex user interfaces tremendously.

Note

It is worth emphasizing that React is not a great solution if you're working on a very simple user interface. If you can solve a problem with a few lines of vanilla JavaScript code, there is probably no strong reason to integrate React into the project.

Looking at React code for the first time, it can look very unfamiliar and strange. It's not what you're used to from JavaScript. Still, it is JavaScript—just enhanced with this JSX feature and various React-specific functionalities (like State). It may be less confusing if you remember that you typically define your user interface (i.e., your content and its structure) with HTML. You don't write step-by-step instructions there either, but rather create a nested tree structure with HTML tags. You express your content, the meaning of different elements, and the hierarchy of your user interface by using different HTML elements and by nesting HTML tags.

If you keep this in mind, the "traditional" (vanilla JavaScript) approach of manipulating the UI should seem rather odd. Why would you start defining low-level instructions like "insert a paragraph element below this button and set its text to <some text>" if you don't do that in HTML at all? React in the end brings back that HTML syntax, which is far more convenient when it comes to defining content and structure. With React, you can write dynamic JavaScript code side-by-side with the UI code (i.e., the HTML code) that is affected by it or related to it.

How React Manipulates the DOM

As mentioned earlier, when writing React code, you typically write it as shown above: You blend HTML with JavaScript code by using the JSX syntax extension.

It is worth pointing out that JSX code does not run like this in browsers. It instead needs to be pre-processed before deployment. The JSX code must be transformed to regular JavaScript code before being served to browsers. The next chapter will take a closer look at JSX and what it's transformed to. For the moment, though, simply keep in mind that JSX code must be transformed.

Nonetheless, it is worth knowing that the code to which JSX will be transformed will also not contain any DOM instructions. Instead, the transformed code will execute various utility methods and functions that are built-into React (in other words, those that are provided by the React package that needs to be added to every React project). Internally, React creates a virtual DOM-like tree structure that reflects the current state of the user interface. This book takes a closer look at this abstract, virtual DOM and how React works in Chapter 9, Behind the Scenes of React and Optimization Opportunities. Therefore, React (the library) splits its core logic across two main packages:

  • The main react package
  • And the react-dom package

The main react package is a third-party JavaScript library that needs to be imported into a project to use React's features (like JSX or state) there. It's this package that creates this virtual DOM and derives the current UI state. But you also need the react-dom package in your project if you want to manipulate the DOM with React.

The react-dom package, specifically the react-dom/client part of that package, acts as a "translation bridge" between your React code, the internally generated virtual DOM, and the browser with its actual DOM that needs to be updated. It's the react-dom package that will produce the actual DOM instructions that will select, update, delete, and create DOM elements.

This split exists because you can also use React with other target environments. A very popular and well-known alternative to the DOM (i.e., to the browser) would be React Native, which allows developers to build native mobile apps with help of React. With React Native, you also include the react package into your project, but in place of react-dom, you would use the react-native package. In this book, "React" refers to both the react package and the "bridge" packages (like react-dom).

Note

As mentioned earlier, this book focuses on React itself. The concepts explained in this book, therefore, will apply to both web browsers and websites as well as mobile devices. Nonetheless, all examples will focus on the web and react-DOM since that avoids introducing extra complexity.

 

Introducing Single Page Applications

React can be used to simplify the creation of complex user interfaces, and there are two main ways of doing that:

  1. Manage parts of a website (e.g., a chat box in the bottom left corner).
  2. Manage the entire page and all user interaction that occurs on it.

Both approaches are viable, but the more popular and common scenario is the second one: Using React to manage the entire web page, instead of just parts of it. This approach is more popular because most websites that have complex user interfaces, have not just one complex element but multiple elements on their pages. Complexity would actually increase if you were to start using React for some website parts without using it for other areas of the site. For this reason, it's very common to manage the entire website with React.

This doesn't even stop after using React on one specific page of the site. Indeed, React can be used to handle URL path changes and update the parts of the page that need to be updated in order to reflect the new page that should be loaded. This functionality is called routing and third-party packages like react-router-dom (see Chapter 12, Multipage Apps with React Router), which integrate with React, allow you to create a website wherein the entire user interfaces is controlled via React.

A website that does not just use React for parts of its pages but instead for all subpages and for routing is called a Single Page Application (SPA) because it consists of only one HTML file (typically named index.html) which is used to initially load the React JavaScript code. Thereafter, the React library and your React code take over and control the actual user interface. This means that the entire user interface is created and managed by JavaScript via React and your React code.

Creating a React Project

To work with React, the first step is the creation of a React project. This can be done in multiple ways, but the most straightforward and easiest way is to use the create-react-app utility command line tool. This is a tool maintained by (parts of) the React team, and you can install it as a Node.js package via the Node Package Manager (npm). Once installed, this tool can be used to create a project folder that comes with React pre-installed, as well as some other tools, such as the Jest package for automated testing.

You need a project setup like this because you typically use features like JSX which wouldn't work in the browser without prior code transformation. Therefore, as mentioned earlier, a pre-processing step is required, and the React project created via create-react-app includes such a step as part of the code build workflow.

To create a project with create-react-app, you must have Node.js installed—preferably the latest (or latest LTS) version. You can get the official Node.js installer for all operating systems from https://nodejs.org/. Once you have installed Node.js, you will also gain access to the built-in npm and npx commands, which you can use to utilize the create-react-app package to create a new project.

You can run the following command inside of your command prompt (Windows), bash (Linux), or terminal (macOS) program. Just make sure that you navigated (via cd) into the folder in which you want to create your new project.

npx create-react-app my-react-project

This command will create a new subfolder with a basic React project setup (i.e., with various files and folders) in the place where you ran it. You should run it in some path on your system where you have full read and write access and where you're not conflicting with any system or other project files.

The exact project structure (that is, the file names and folder names) may vary over time, but generally, every new React project contains a couple of key files and folders:

  • A src/ folder that contains the main source code files for the project:
    • An index.js file which is the main entry script file that will be executed first
    • An App.js file which contains the root component of the application (you'll learn more about components in the next chapter)
    • Various styling (*.css) files that are imported by the JavaScript files
    • Other files, like code files for automated tests
  • A public/ folder which contains static files that will be part of the final website:
    • This folder may contain static images like favicons
    • The folder also contains an index.html file which is the single HTML page of this website
  • package.json and package-lock.json are files that manage third-party dependencies of your project:
    • Production dependencies like react or react-dom
    • Development dependencies like jest for automated tests

    Note

    package.json is the file in which you actually manage packages and their versions. package-lock.json is created automatically (by Node.js). It locks in exact dependency and sub-dependency versions, whereas package.json only specifies version ranges. You can learn more about these files and package versions on https://docs.npmjs.com/.

  • The node_modules folder holds the actual third-party package code of the packages that are listed in the package.json file. This node_modules folder can be deleted since you can recreate it by running npm install inside of the project folder

Most of the React code will be written in the App.js file or custom components that will be added to the project. This book will explore components in the next chapter.

Note

The node_modules folder can become very big since it contains all projects dependencies and dependencies of dependencies. Therefore, it's typically not included if projects are shared with other developers or pushed to GitHub. The package.json file is all you need. By running npm install, the node_modules folder will be recreated locally.

Once the project is created, you can start writing your code. To preview your code on a live website locally on your system, you can run npm start inside of the project folder. This will start a built-in development server that pre-processes, builds, and hosts your React-powered SPA. This process should normally open the preview page in a new browser tab automatically. If that doesn't happen, you can manually open a new tab and navigate to localhost:3000 there (unless you see a different address as output in the window where you executed npm start, in which case, use the address that's shown after you ran npm start).

The preview website that opens up will automatically reload and reflect code changes whenever you save changes to your code.

When you're done with development for the day, you can quit the running development server process via CTRL + C (in the command prompt or terminal window where you started it via npm start). To continue development and get back that live preview website, you can always restart it by running npm start (inside of the project folder) again.

 

Summary and Key Takeaways

  • React is a library, though it's actually a combination of two main packages: react and react-dom.
  • Though it is possible to build non-trivial user interfaces without React, simply using vanilla JavaScript to do so can be cumbersome, error-prone, and hard to maintain.
  • React simplifies the creation of complex user interfaces by providing a declarative way to define the desired end state(s) of the UI.
  • Declarative means that you define the target user interface content and structure, combined with different states (e.g., "is a modal open or closed?"), and you leave it up to React to figure out the appropriate DOM instructions.
  • The react package itself derives UI states and manages a virtual DOM. It's "bridges" like react-dom or react-native that translate this virtual DOM into actual UI (DOM) instructions.
  • With React, you can build Single Page Applications (SPAs), meaning that React is used to control the entire user interface on all pages as well as the routing between pages.
  • React projects can be created with help of the create-react-app package, which provides a readily configured project folder and a live preview development server.

What's Next?

At this point, you should have a basic understanding of what React is and why you might consider using it, especially for building non-trivial user interfaces. You learned how to create new React projects with create-react-app, and you are now ready to dive deeper into React and the actual key features it offers.

In the next chapter, you will learn about a concept called components which are the fundamental building blocks of React apps. You will learn how components are used to compose user interfaces and why those components are needed in the first place. The next chapter will also dive deeper into JSX and explore how it is transformed to regular JavaScript code and which kind of code you could write alternatively to JSX.

Test Your Knowledge!

Test your knowledge about the concepts covered in this chapter by answering the below questions. You can then compare your answers to example answers that can be found here: https://packt.link/ENPda.

  1. What is React?
  2. Which advantage does React offer over vanilla JavaScript projects?
  3. What's the difference between imperative and declarative code?
  4. What is a Single-Page-Application (SPA)?
  5. How can you create new React projects and why do you need such a more complex project setup?
About the Author
  • Maximilian Schwarzmüller

    Academind GmbH - Online Education: Bundling the courses and know-how of successful instructors, Academind strives to deliver high-quality online education. Online education, real-life success—that's what Academind stands for. Learn topics such as web development, data analysis, and more in a fun and engaging way. Maximilian Schwarzmüller: Since the age of 13, Maximilian Schwarzmüller has never stopped learning new programming skills and languages. In the early days, he started creating websites for friends and for fun. This passion has remained and shaped his decision to work as a freelance web developer and consultant. The success and fun he has in this job is immense and really keeps that passion alive. Although he started web development on the backend (PHP with Laravel and NodeJS), he has increasingly become a front-end developer using modern frameworks such as React, Angular, or VueJS 2 in a lot of projects. As a self-taught developer, he had broadened his horizon by studying business administration, resulting in a master's degree. This enabled him to work in a major strategy consultancy as well as a bank. Whilst learning and developing his skills, he realized that he enjoyed development more than these fields. As a self-taught professional, Max is familiar with the difficult topics when learning new or improving on already-known languages. This background and experience enables him to focus on the most relevant key concepts and topics. His track record is the best proof of that. Whether working as a development instructor or teaching business administration, he always receives great feedback. The most rewarding experience is to see how people find new and better jobs, build awesome web applications, acquire amazing projects, or simply enjoy their hobby with the help of his content.

    Browse publications by this author
React Key Concepts
Unlock this book and the full library FREE for 7 days
Start now