Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
React Key Concepts
React Key Concepts

React Key Concepts: An in-depth guide to React's core features , Second Edition

Arrow left icon
Profile Icon Maximilian Schwarzmüller
Arrow right icon
Can$63.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (6 Ratings)
Paperback Feb 2025 544 pages 2nd Edition
eBook
Can$44.99 Can$50.99
Paperback
Can$63.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Maximilian Schwarzmüller
Arrow right icon
Can$63.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (6 Ratings)
Paperback Feb 2025 544 pages 2nd Edition
eBook
Can$44.99 Can$50.99
Paperback
Can$63.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
Can$44.99 Can$50.99
Paperback
Can$63.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

React Key Concepts

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
  • Explain the difference between imperative and declarative code
  • Differentiate between single-page applications (SPAs) and multi-page apps
  • 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 2023 Stack Overflow developer survey. It is currently used by over 5% of the top 1,000 websites and compared to other popular frontend JavaScript libraries and frameworks like Angular, React is leading by a huge margin, when looking at key metrics like weekly package downloads via npm, 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’ll likely be able to learn advanced concepts quicker and avoid errors when trying 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 read this chapter first.

What is React?

React is a JavaScript library, and if you take a look at the official web page (the official React website and documentation are available at this link: https://react.dev/), you learn that the creators call it “The library for web and native user interfaces.”

But what does this mean?

First, it’s important to understand that React is a JavaScript library. As a reader of this book, you know what JavaScript is and why you use JavaScript in the browser. JavaScript allows you to add interactivity to your website since, with JavaScript, you can react to user events and manipulate the page after it is loaded. This is extremely valuable as it allows you to build highly interactive web user interfaces (UIs).

But what is a “library” and how does React help with building UIs?

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 can help you write more concise and possibly also less error-prone code and enable you to implement certain features more quickly.

React is such a library – one that focuses on providing functionalities that help you create interactive and reactive UIs. Indeed, React deals with more than web interfaces (i.e., websites loaded in browsers). You can also build native apps for mobile devices with React and React Native, which is another library that utilizes React under the hood. 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. No matter which platform you’re targeting though, creating interactive UIs with just JavaScript can quickly become very complex and overwhelming.

The Problem with “Vanilla JavaScript”

Vanilla JavaScript is a term commonly used in web development to refer 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 UIs and websites can quickly become very hard to manage with vanilla JavaScript.

React simplifies the creation and management of such UIs 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, the idea behind “imperative versus 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.

Let’s look at a short code snippet that shows how you could handle the following UI 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 later). But even though this example is straightforward to digest, working with vanilla JavaScript will quickly reach its limits for feature-rich UIs and the code to handle various user interactions accordingly also becomes more complex. Code can quickly grow significantly, so maintaining it can become a challenge.

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

The code shown previously could be translated into these more human-readable instructions:

  1. Look for an HTML element of the button type 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.

However, when working with UIs, 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 Document Object Model (DOM) instructions that allow your code to interact with elements, add elements, manipulate elements, and so on.

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

As a result, 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. 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 UIs 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.

The button-clicking example 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. Also, 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. Here, you will find a screenshot of some example code for the described use case.

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 UI is likely to look.

A screenshot of a computer program

Description automatically generated

Figure 1.1: An example JavaScript code file that contains over 100 lines of code for a fairly trivial UI

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://www.toptal.com/developers/javascript-minifier) 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 UI with only basic functionality. The actual business logic (i.e., input validation, determining whether and when overlays should be shown, and defining the output text) only makes up a small fraction of the overall code base – around 20 to 30 lines of code, in this case (around 20 after minifying).

That’s roughly 75% of the 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 earlier, 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 a new text once the click on the button occurs.

Nonetheless, this code looks totally different – like a mixture of JavaScript and HTML. Indeed, React uses a syntax extension called JSX (i.e., JavaScript extended to include XML-like syntax). For the moment, it’s enough to understand that this JSX code will work because of a pre-processing (or transpilation) 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 it is deployed. This allows for development-only syntax like JSX, which would not work in the browser and is for that reason transformed to regular JavaScript before deployment. (You’ll get a thorough introduction to JSX in Chapter 2, Understanding React Components and JSX.)

In addition, the snippet shown previously 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 states with React). For the moment, you can think of this state as a variable that, when changed, will trigger React to update the UI 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 the 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 hence, 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 and updating its textContent). Instead, you will hand this work off to React. You will only need to focus on the desired end states 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 to do 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 UI, 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.

A screenshot of a computer program

Description automatically generated

Figure 1.2: The code snippet from before is 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. However, 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.

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 states 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 UIs tremendously.

Note

It is worth emphasizing that React is not a great solution if you’re working on a very simple UI. 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 UI (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 UI by using different HTML elements and 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 previously: 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 into regular JavaScript code before being served to browsers. The next chapter will take a closer look at JSX and what it’s transformed into. 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 need to be added to every React project). Internally, React creates a virtual DOM-like tree structure that reflects the current state of the UI. This book takes a closer look at this abstract, virtual DOM, and how React works in Chapter 10, Behind the Scenes of React and Optimization Opportunities. That’s why React (the library) splits its core logic across two main packages:

  • The main react package
  • 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 the help of React. With React Native, you also include the react package in 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 SPAs

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

  • Manage parts of a website (e.g., a chat box in the bottom left corner).
  • Manage the entire page and all user interactions that occur 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 UIs have not just one, but multiple complex 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 13, Multipage Apps with React Router), which integrate with React, allow you to create a website wherein the entire UI 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 often built as a SPA because it’s common to create React projects that contain 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 UI. This means that the entire UI is created and managed by JavaScript via React and your React code.

That being said, it’s also becoming more and more popular to build full-stack React apps, where frontend and backend code are merged. Modern React frameworks like Next.js simplify the process of building such web apps. Whilst the core concepts are the same, no matter which kind of application is built, this book will explore full-stack React app development in greater detail in Chapter 15, Server-side Rendering & Building Fullstack Apps with Next.js, Chapter 16, React Server Components and Server Actions and Chapter 17, Understanding React Suspense and the use() Hook.

Ultimately, this book prepares you for working with React on all kinds of React projects since the core building blocks and key concepts are always the same.

Creating a React Project with Vite

To work with React, the first step is the creation of a React project. The official documentation recommends using a framework like Next.js. But while this might make sense for complex web applications, it’s overwhelming for getting started with React and for exploring React concepts. Next.js and other frameworks introduce their own concepts and syntax. As a result, learning React can quickly become frustrating since it can be difficult to tell React features apart from framework features. In addition, not all React apps need to be built as full-stack web apps – consequently, using a framework like Next.js might add unnecessary complexity.

That’s why Vite-based React projects have emerged as a popular alternative. Vite is an open-source development and build tool that can be used to create and run web development projects based on all kinds of libraries and frameworks – React is just one of the many options.

Vite creates projects that come with a built-in, preconfigured build process that, in the case of React projects, takes care of the JSX code transpilation. It also provides a development web server that runs locally on your system and allows you to preview the React app while you’re working on it.

You need a project setup like this because React projects typically use features like JSX, which wouldn’t work in the browser without prior code transformation. Hence, as mentioned earlier, a pre-processing step is required.

To create a project with Vite, 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 command, which you can use to utilize the Vite package to create a new React project.

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

npm create vite@latest my-react-project

Once executed, this command will prompt you to choose a framework or library you want to use for this new project. You should choose React and then JavaScript.

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.

It’s worth noting that the project creation command does not install any required dependencies such as the React library packages. For that reason, you must navigate into the created folder in your system terminal or command prompt (via cd my-react-project) and install these packages by running the following command:

npm install

Once the installation finishes successfully, the project setup process is complete.

To view the created React application, you can start a development server on your machine via this command:

npm run dev

This invokes a script provided by Vite, which will spin up a locally running web server that pre-processes, builds, and hosts your React-powered SPA – by default on localhost:5173. Therefore, while working on the code, you typically have this development server up and running as it allows you to preview and test code changes.

Best of all, this local development server will automatically update the website whenever you save any code changes, hence allowing you to preview your changes almost instantly.

You can quit this server whenever you’re done for the day by pressing Ctrl + C in the terminal or command prompt where you executed npm run dev.

Whenever you’re ready to start working on the project again, you can restart the server via npm run dev.

Note

In case you encounter any issues with creating a React project, you can also download and use the following starting project: https://github.com/mschwarzmueller/book-react-key-concepts-e2/tree/01-what-is-react/react-starting-project. It’s a project created via Vite, which can be used in the same way as if it were created with the preceding command.

When using this starting project (or, in fact, any GitHub-hosted code snapshot belonging to this book), you need to run npm install in the project folder first, before running npm run dev.

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

  • A src/ folder, which contains the main source code files for the project:
    • A main.jsx file, which is the main entry script file that will be executed first
    • An App.jsx file, which contains the root component of the application (you’ll learn more about components in the next chapter)
    • Various styling (*.css) files, which are imported by the JavaScript files
    • An assets/ folder that can be used to store images or other assets that should be used in your React code
  • A public/ folder, which contains static files that will be part of the final website (e.g., a favicon)
  • An index.html file, which is the single HTML page of this website
  • package.json and package-lock.json are files that list and define the third-party dependencies of your project:
    • Production dependencies like react or react-dom
    • Development dependencies like eslint for automated code quality checks
  • Other project configuration files (e.g., .gitignore for managing Git file tracking)
  • A node_modules folder, which contains the actual code of the installed third-party packages

It’s worth noting that App.jsx and main.jsx use .jsx as a file extension, not .js. This is a file extension that’s enforced by Vite for files that do not just contain standard JavaScript but also JSX code. When working on a Vite project, most of your project files will consequently use .jsx as an extension.

Almost all of the React-specific code will be written in the App.jsx file or custom component files that will be added to the project. We will explore components in the next chapter.

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 at https://docs.npmjs.com/.

The code of the project’s dependencies is stored in the node_modules folder. This folder can become very big since it contains the code of all installed packages and their dependencies. For that reason, 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.

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 UIs without React, simply using vanilla JavaScript to do so can be cumbersome, error prone, and hard to maintain.
  • React simplifies the creation of complex UIs by providing a declarative way to define the desired end states of the UI.
  • Declarative means that you define the target UI 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 is a “bridge,” like react-dom or react-native, that translates this virtual DOM into actual UI (DOM) instructions.
  • With React, you can build SPAs, meaning that React is used to control the entire UI on all pages as well as the routing between pages.
  • You can also use React, in combination with frameworks like Next.js, to build full-stack web applications where server- and client-side code are connected.
  • React projects can be created with the help of the Vite 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 UIs. You learned how to create new React projects with Vite, 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 UIs 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 into 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 following questions. You can then compare your answers to example answers that can be found here: https://github.com/mschwarzmueller/book-react-key-concepts-e2/blob/01-what-is-react/exercises/questions-answers.md.

  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 complex project setup?

Join Us on Discord

Read this book alongside other users, AI experts, and the author himself.

Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/ReactKeyConcepts2e

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Work through clear, concise explanations of core React 19 functionalities
  • Complete practical exercises that challenge you to build your own simple apps
  • Discover fullstack React with Next.js, React Server Components, Suspense, and more

Description

Maximilian Schwarzmüller is a bestselling instructor who has helped more than three million students worldwide learn how to code. His bestselling React video course, “React – The Complete Guide”, has over nine hundred thousand students on Udemy. Max has written this quick-start reference that distills the core concepts of React. Simple explanations, relevant examples, and step-by-step derivations make this guide the ideal resource for busy developers. In this second edition, Max guides you through changes brought by React 19, including the new use() hook, form actions, and how to think about React on the server. This book will support you through your next React projects in giving you a behind-the-scenes understanding of the framework – whether you've just finished Max's video course and are looking for a handy reference, or you’re using a variety of other learning materials and need a single study guide to bring everything together. You’ll find full solutions to all end-of-chapter quizzes and exercises in the book’s GitHub repository.

Who is this book for?

This React book is for developers who have prior experience with, or who are currently learning, the basics of React. You can use this book as a standalone resource to consolidate your understanding or as a companion guide to other courses. To get the most value from this book, you should have a basic understanding of the fundamentals of JavaScript, HTML, and CSS.

What you will learn

  • Build modern, user-friendly, and reactive web apps
  • Create components and utilize props to pass data between them
  • Handle events, perform state updates, and manage conditional content
  • Add styles dynamically and conditionally for modern user interfaces
  • Use advanced state management techniques such as React's Context API
  • Utilize React Router to render different pages for different URLs
  • Understand key best practices and optimization opportunities
  • Learn about React Server Components and Server Actions
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Last updated date : Feb 11, 2025
Publication date : Jan 14, 2025
Length: 544 pages
Edition : 2nd
Language : English
ISBN-13 : 9781836202271
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Last updated date : Feb 11, 2025
Publication date : Jan 14, 2025
Length: 544 pages
Edition : 2nd
Language : English
ISBN-13 : 9781836202271
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Table of Contents

20 Chapters
React – What and Why Chevron down icon Chevron up icon
Understanding React Components and JSX Chevron down icon Chevron up icon
Components and Props Chevron down icon Chevron up icon
Working with Events and State Chevron down icon Chevron up icon
Rendering Lists and Conditional Content Chevron down icon Chevron up icon
Styling React Apps Chevron down icon Chevron up icon
Portals and Refs Chevron down icon Chevron up icon
Handling Side Effects Chevron down icon Chevron up icon
Handling User Input & Forms with Form Actions Chevron down icon Chevron up icon
Behind the Scenes of React and Optimization Opportunities Chevron down icon Chevron up icon
Working with Complex State Chevron down icon Chevron up icon
Building Custom React Hooks Chevron down icon Chevron up icon
Multipage Apps with React Router Chevron down icon Chevron up icon
Managing Data with React Router Chevron down icon Chevron up icon
Server-side Rendering & Building Fullstack Apps with Next.js Chevron down icon Chevron up icon
React Server Components & Server Actions Chevron down icon Chevron up icon
Understanding React Suspense & The use() Hook Chevron down icon Chevron up icon
Next Steps and Further Resources Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(6 Ratings)
5 star 83.3%
4 star 16.7%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Jonathan Reeves Jan 24, 2025
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are new to React or an experienced developer seeking to stay updated on the latest trends and best practices, "React Key Concepts" is an invaluable resource. This book provides comprehensive guidance on utilizing essential libraries, such as react-router-dom, effectively. I highly recommend this book, as it has proven to be a significant asset in my daily work as a React developer.Max, an exceptional instructor, demonstrates extensive knowledge of the subject matter. Having previously taken his courses on Udemy, I appreciate his engaging writing style, which keeps the reader captivated and eager to learn more. The book effectively combines theoretical concepts with numerous code examples and snippets, facilitating a deeper understanding of the material.For anyone looking to enhance their grasp of React's core concepts, "React Key Concepts: An In-Depth Guide to React's Core Features" is an excellent choice.I just received my paperback copy and I have to say this book is just an amazing resource for anyone that uses React for work or even if you are just starting your journey. What a great resource. Read more
Amazon Verified review Amazon
Aram Jan 28, 2025
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've got the chance to read this book from an Advanced Reader's Copy shared with me by the Publisher.It is a great resource to complement your learning journey in building modern web apps.This book will teach you every essential concept in React.Highly important topics are covered in details, such as:- Components and JSX- Passing and consuming props for reusability- Building interactive UIs with Events, State and Hooks- Lists Rendering and displaying conditional content- Styling React with CSS and styling libraries- Accessing DOM values with refs- Building SPA using React Router- Form Actions to handle user input- Handling complex state- Best practices and optimizations in ReactOne of the most important topics that is covered in detail is the side effects.Tasks such as calling external APIs, accessing browser storage, and other similar tasks are considered side effects and should be handled correctly to avoid issues with React’s component rendering lifecycle.Another equally important topic, Context API - a modern way to pass props deeply into components, is also covered extensivelyBoth of these topics have been my favourite read on this amazing book.The author even goes beyond the frontend, and taps into building full stack web applications by using the popular Next.js: A powerful react-based framework to allow you build server-side rendered react apps.The book has recently been released with the announcement of the latest version of React 19, so you don’t need to worry about missing learning the new features as well.Recent features including use() hook, form actions, and how to think about React on the server, are all covered.The book is full of screenshots and code snippets to better simplify your learning experience.Also I really like how there are exercises and quizzes by the end of each chapter, this can massively boost your learning experience and a perfect opportunity to test your knowledge.Always keep in mind that the more you implement and write code by yourself, the better skilled and confident you will become.This is a highly recommended read.Don’t miss the chance to master React from one of the best React instructors. Read more
Amazon Verified review Amazon
Ralph B. Jan 24, 2025
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great teacher. Read more
Amazon Verified review Amazon
Joseph Kellerer Apr 28, 2025
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I already knew Maximilian Schwarzmüller from his Udemy courses. Having those lessons in a book form, is easier to lookup special topics.
Feefo Verified review Feefo
Attila Fekete May 14, 2025
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book, in depth and very well structured. I love it!
Feefo Verified review Feefo
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon