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

React Key Concepts: Consolidate your knowledge of React's core features

Arrow left icon
Profile Icon Maximilian Schwarzmüller
Arrow right icon
$44.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (61 Ratings)
Paperback Dec 2022 590 pages 1st Edition
eBook
$9.99 $35.99
Paperback
$44.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Maximilian Schwarzmüller
Arrow right icon
$44.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (61 Ratings)
Paperback Dec 2022 590 pages 1st Edition
eBook
$9.99 $35.99
Paperback
$44.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $35.99
Paperback
$44.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
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

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?
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A clear, concise explanation of core React 18 functionalities to promote quick, easy reference
  • Gain a deep understanding of key React concepts with the help of step-by-step derivations
  • Work with practical exercises that challenge you to apply your new skills and build your own simple apps

Description

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.

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 a more in-depth course. 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
  • Apply styles dynamically and conditionally to create a modern UI
  • 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
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
Publication date : Dec 26, 2022
Length: 590 pages
Edition : 1st
Language : English
ISBN-13 : 9781803234502
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
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

Publication date : Dec 26, 2022
Length: 590 pages
Edition : 1st
Language : English
ISBN-13 : 9781803234502
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

Frequently bought together


Stars icon
Total $ 139.97
React Application Architecture for Production
$44.99
React and React Native
$49.99
React Key Concepts
$44.99
Total $ 139.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. React – What and Why Chevron down icon Chevron up icon
2. Understanding React Components and JSX Chevron down icon Chevron up icon
3. Components and Props Chevron down icon Chevron up icon
4. Working with Events and State Chevron down icon Chevron up icon
5. Rendering Lists and Conditional Content Chevron down icon Chevron up icon
6. Styling React Apps Chevron down icon Chevron up icon
7. Portals and Refs Chevron down icon Chevron up icon
8. Handling Side Effects Chevron down icon Chevron up icon
9. Behind the Scenes of React and Optimization Opportunities Chevron down icon Chevron up icon
10. Working with Complex State Chevron down icon Chevron up icon
11. Building Custom React Hooks Chevron down icon Chevron up icon
12. Multipage Apps with React Router Chevron down icon Chevron up icon
13. Managing Data with React Router Chevron down icon Chevron up icon
14. Next Steps and Further Resources 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.9
(61 Ratings)
5 star 91.8%
4 star 4.9%
3 star 1.6%
2 star 1.6%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Vincenzo Jun 22, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have worked with React.js for more than 5 years, I decided to buy this book to refresh my knowledge of the latest best practices.And I must say, the book exceeded my expectations. I quickly came up to speed with unfamiliar concepts, and was then able to refactor/improve my own sets of code, all while gaining a better understanding of React.js from the inside out thanks to chapters 9, 10 and 11.I know Maximilian has a deep knowledge of React having followed his online courses and this book just confirmed how great he is as a Teacher.I definitely recommend this book.
Amazon Verified review Amazon
Carl KK L Feb 18, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
In retrospect, I feel immensely thankful to have discovered Maximilian Schwarzmüller, the author of this book, during the early stage when I just embarked on my career as a developer. Specifically, I took his 100 Days of Code - Web Development Bootcamp on Udemy and, upon completing the course, was able to develop a full-stack web application that had all the functions a standard web app should have, complete with satisfying UI/UX created with the CSS, JavaScript, and Bootstrap knowledge he provided. Maximilian also introduced just enough advanced concepts to ensure that learners not only knew the how, but also the what and why behind the scenes, a crucial aspect of becoming a good web developer.Maximilian also has another online course, React: The Complete Guide, which a friend of mine completed last year. With the knowledge gained from that course alone, my friend secured a frontend developer job requiring React skills and has worked in that position for over six months. This is a testament to the quality of the author and his resources.Now, let's discuss the book itself, focusing on both its form and content.Form:You may be wondering why someone would choose a book over an online video course. As it turns out, our brains process abstract and image content in different regions, which makes it challenging for the brain to achieve high concurrency. This task-switching burden reduces learning efficiency and hinders a learner's ability to digest, ponder, and reflect on the knowledge they have gained. While it's possible to pause, slow down, or speed up a video to accommodate one's pace, it can also be a significant distraction when attempting to understand difficult content. In contrast, a book allows you to ruminate and brainstorm as you learn, connecting the new information with your existing knowledge and forming new synapses. Additionally, a book is a useful reference tool, easy to consult when revisiting a concept or checking certain information. This convenience is not possible with a video course unless you create your own notes with good indexing (which I recommend using the Obsidian app for).Content:Maximilian's book is an outstanding resource for anyone interested in learning the basics of React. The content is well-structured and easy to follow, even if you have very little experience with React (although, as the author clearly states, some fundamental knowledge of JavaScript, HTML, and CSS is necessary). For every concept introduced in React, there are code snippet examples that make it feel like someone is holding your hand and guiding you step by step to proficiency. You can experiment and amend the codes the book provides on your own IDE to gain a deeper understanding through hands-on experience. For more advanced learners, there are additional resources available, such as links to other articles for those who want to delve deeper into the topic. Maximilian also provides insight into the mechanisms of React working behind the scenes of the codes, so you can continue to learn even if you already have some experience with React.Overall, I highly recommend this book to anyone looking to learn React. Maximilian has done an excellent job presenting the material in a clear and accessible way, and you can easily apply the knowledge you gain to real-life projects.
Amazon Verified review Amazon
AL Jan 31, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This react book helped me learn the ins and outs of react that I did not learn from tutorials on the internet. I found chapter 9: Behind the Scenes of React and Optimization Opportunities, to be useful as It filled in the gaps of my react knowledge, especially as a beginner who needs to refresh my knowledge often. I find this book to be helpful to my needs because I am graduating college this year and I think this book will help out in an entry level developer job. The book is well put together and is easy to follow along. I would recommend this book to anyone starting out with react.
Amazon Verified review Amazon
dramiro Jan 31, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The writer has extensive teaching experience, with extensive course content on platforms such as Udemy.In this book he demonstrates his ability to transmit his knowledge, explaining in detail each topic of React.The book is a book with interesting topics, suitable for someone who is just starting with React, as well as for an experienced developer who needs to reinforce his knowledge. Max explains in detail the concepts and accompanies them with very good code examples where you can better understand the theory.A great book to have at your fingertips and to be able to consult your doubts on a daily basis.
Amazon Verified review Amazon
J.P.G. Apr 11, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I had the opportunity to dive into React Key Concepts, and I must say, it's a great book whether you're a React beginner, or a seasoned developer! What I really appreciated about this book is its well-structured and concise approach to the fundamentals of React. It starts with a clear introduction to React and JSX, and then it jumps straight into the meat of React with components, props, events, and state. This is followed by more advanced topics such as custom hooks and React Router, which are essential skills for building complex React apps.The practical exercises are where this book really shines! They offer the perfect mix of challenge and guidance, allowing me to apply what I've learned in a hands-on way. The pacing of the book is also commendable, with a quick-paced overview that doesn't drag on too long.One thing to note is that the book leans more towards React-specific concepts rather than JavaScript foundations, but that's not necessarily a bad thing. If you're new to JavaScript, it's best to pair this book with an introductory text on JS, so you're well-versed in the language before diving into React's nitty-gritty.React Key Concepts is an expertly written and comprehensive book, which I highly recommend to anyone interested in learning or improving their knowledge of React or frontend development in general. Overall, a great source of information and a worthwhile investment in your React skills.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

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