01 Why React?
What is React?
I think the one-line description of React on its home page (https://react.dev/) is concise and accurate:
“A JavaScript library for building user interfaces.”
我认为React主页(https://react.dev/)上的一行描述既简洁又准确:
“用于构建用户界面的JavaScript库。”
It’s a library for building User Interfaces (UIs). This is perfect because, as it turns out, this is all we want most of the time. I think the best part about this description is everything that it leaves out. It’s not a mega framework. It’s not a full-stack solution that’s going to handle everything from the database to real-time updates over WebSocket connections. We might not actually want most of these prepackaged solutions. If React isn’t a framework, then what is it exactly?
它是一个用于构建用户界面(ui)的库。这是完美的,因为事实证明,这是我们大多数时候想要的。我认为这个描述最好的部分是它遗漏的一切。这不是一个大型框架。它不是一个全栈解决方案,它将处理从数据库到通过WebSocket连接的实时更新的所有事情。实际上,我们可能并不需要这些预先包装好的解决方案。如果React不是一个框架,那么它到底是什么?
React is just the view layer
React is generally thought of as the view layer in an application. You might have used a library such as Handlebars or jQuery in the past. Just as jQuery manipulates UI elements and Handlebars templates are inserted into a page, React components change what the user sees. The following diagram illustrates where React fits in our frontend code:
React通常被认为是应用程序中的视图层。您可能在过去使用过Handlebars或jQuery之类的库。就像jQuery操纵UI元素和把手栏模板插入页面一样,React组件改变用户看到的内容。下图说明了React在我们前端代码中的位置:
This is all there is to React – the core concept. Of course, there will be subtle variations to this theme as we make our way through the book, but the flow is more or less the same. We have some application logic that generates some data. We want to render this data to the UI, so we pass it to a React Component, which handles the job of getting the HTML into the page.You may wonder what the big deal is; React appears to be yet another rendering technology. We’ll touch on some of the key areas where React can simplify application development in the remaining sections of the chapter.
这就是React的核心概念。当然,在我们读这本书的过程中,这个主题会有微妙的变化,但流程或多或少是相同的。我们有一些生成数据的应用程序逻辑。我们希望将这些数据呈现给UI,所以我们将其传递给React组件,该组件负责将HTML输入页面。你可能想知道这有什么大不了的;React似乎是另一种渲染技术。在本章的其余部分中,我们将涉及React可以简化应用程序开发的一些关键领域。
Simplicity is good
React doesn’t have many moving parts to learn about and understand. Internally, there’s a lot going on, and we’ll touch on these things throughout the book. The advantage of having a small API to work with is that you can spend more time familiarizing yourself with it, experimenting with it, and so on. The opposite is true of large frameworks, where all of your time is devoted to figuring out how everything works. The following diagram gives you a rough idea of the APIs that we have to think about when programming with React:
React没有太多需要学习和理解的活动部件。在内部,有很多事情正在发生,我们将在书中触及这些事情。使用小型API的好处是,您可以花更多的时间来熟悉它、试验它等等。大型框架的情况正好相反,在大型框架中,您的所有时间都用于弄清楚所有内容是如何工作的。下图给出了我们在使用React编程时必须考虑的api的大致概念:
React is divided into two major APIs:
- The React Component API: These are the parts of the page that arerendered by the React DOM.
- React DOM: This is the API that’s used to perform the rendering on a web page.
Within a React component, we have the following areas to think about:
- Data: This is data that comes from somewhere (the component doesn’tcare where) and is rendered by the component.
- Lifecycle: This consists of methods or Hooks that we implement to respond to the component’s entering and exiting phases of the React rendering process as they happen over time – for example, one phase of the life cycle is when the component is about to be rendered.
- Events: These are the code that we write for responding to user interactions.
- JSX: This is the syntax of React components used to describe UI structures.
Don’t fixate on what these different areas of the React API represent just yet. The takeaway here is that React, by nature, is simple. Just look at how little there is to figure out! This means that we don’t have to spend a ton of time going through API details here. Instead, once you pick up on the basics, we can spend more time on nuanced React usage patterns that fit in nicely with declarative UI structures.
不要只关注React API的这些不同领域代表了什么。这里的要点是,React本质上是简单的。看看有多少东西需要弄清楚!这意味着我们不需要花大量的时间在API细节上。相反,一旦你掌握了基础知识,我们就可以花更多的时间在细致入微的React使用模式上,这些模式可以很好地适应声明式UI结构。
Declarative UI structures
React newcomers have a hard time getting to grips with the idea that components mix in markup with their JavaScript in order to declare UI structures. If you’ve looked at React examples and had the same adverse reaction, don’t worry. Initially, we’re all skeptical of this approach, and I think the reason is that we’ve been conditioned for decades by the separation of concerns principle. This principle states that different concerns, such as logic and presentation, should be separate from one another. Now, whenever we see things mixed together, we automatically assume that this is bad and shouldn’t happen.The syntax used by React components is called JSX (JavaScript XML). A component renders content by returning some JSX. The JSX itself is usually HTML markup, mixed with custom tags for React components. The specifics don’t matter at this point; we’ll go into detail in the coming chapters. What’s groundbreaking about the declarative JSX approach is that we don’t have to perform little micro-operations to change the content of a component.
React新手很难理解组件为了声明UI结构而将标记与JavaScript混合在一起的想法。如果你看过React的例子,也有同样的不良反应,不要担心。最初,我们都对这种方法持怀疑态度,我认为原因是我们几十年来一直受到关注点分离原则的制约。该原则指出,不同的关注点,如逻辑和表示,应该彼此分开。现在,每当我们看到东西混在一起,我们就会自动认为这是不好的,不应该发生。React组件使用的语法称为JSX (JavaScript XML)。组件通过返回一些JSX来呈现内容。JSX本身通常是HTML标记,混合了React组件的自定义标记。在这一点上,细节并不重要;我们将在接下来的章节中详细讨论。声明式JSX方法的突破性之处在于,我们不必执行微小的微操作来更改组件的内容。
Although I won’t be following the convention in this book, some React developers prefer the .jsx extension instead of .js for their components.
虽然我不会遵循本书中的惯例,但一些React开发人员更喜欢使用.jsx扩展名而不是.js。
For example, think about using something such as jQuery to build your application. You have a page with some content on it, and you want to add a class to a paragraph when a button is clicked. Performing these steps is easy enough. This is called imperative programming, and it’s problematic for UI development. While this example of changing the class of an element is simple, real applications tend to involve more than three or four steps to make something happen.React components don’t require you to execute steps in an imperative way. This is why JSX is central to React components. The XML-style syntax makes it easy to describe what the UI should look like – that is, what are the HTML elements that this component is going to render? This is called declarative programming and is very well suited for UI development. Once you’ve declared your UI structure, you need to specify how it changes over time.
例如,考虑使用jQuery之类的东西来构建应用程序。您有一个包含一些内容的页面,并且您希望在单击按钮时向段落添加一个类。执行这些步骤非常简单。这被称为命令式编程,这对UI开发来说是个问题。虽然这个更改元素类的示例很简单,但实际的应用程序往往需要三到四个以上的步骤才能完成某些操作。React组件不要求您以命令式的方式执行步骤。这就是为什么JSX是React组件的核心。xml样式的语法使描述UI应该是什么样子变得很容易——也就是说,这个组件将要呈现的HTML元素是什么?这被称为声明式编程,非常适合UI开发。一旦声明了UI结构,就需要指定它如何随时间变化。
Data changes over time
Another area that’s difficult for React newcomers to grasp is the idea that JSX is like a static string, representing a chunk of rendered output. This is where time and data come into play. React components rely on data being passed into them. This data represents the dynamic parts of the UI – for example, a UI element that’s rendered based on a Boolean value could change the next time the component is rendered. Here’s a diagram illustrating the idea:
React新手很难理解的另一个方面是,JSX就像一个静态字符串,表示大块的渲染输出。这就是时间和数据发挥作用的地方。React组件依赖于传递给它们的数据。这些数据表示UI的动态部分——例如,基于布尔值呈现的UI元素可能在下次呈现组件时发生变化。下面的图表说明了这个想法:
Each time the React component is rendered, it’s like taking a snapshot of the JSX at that exact moment in time. As your application moves forward through time, you have an ordered collection of rendered UI components. In addition to declaratively describing what a UI should be, re-rendering the same JSX content makes things much easier for developers. The challenge is making sure that React can handle the performance demands of this approach.
每次渲染React组件时,就像是在那个时刻拍摄JSX的快照。随着您的应用程序向前移动,您将获得呈现的UI组件的有序集合。除了声明性地描述UI应该是什么之外,重新呈现相同的JSX内容使开发人员更容易完成工作。挑战在于确保React能够处理这种方法的性能需求。
Performance matters
Using React to build UIs means that we can declare the structure of the UI with JSX. This is less error-prone than the imperative approach of assembling the UI piece by piece. However, the declarative approach does present a challenge –performance.For example, having a declarative UI structure is fine for the initial rendering because there’s nothing on the page yet. So, the React renderer can look at the structure declared in JSX and render it in the DOM browser.
使用React构建UI意味着我们可以用JSX声明UI的结构。这比逐块组装UI的命令式方法更不容易出错。然而,声明性方法确实带来了一个挑战——性能。例如,具有声明性UI结构对于初始呈现来说很好,因为页面上还没有任何内容。因此,React渲染器可以查看在JSX中声明的结构,并在DOM浏览器中渲染它。
The Document Object Model (DOM) represents HTML in the browser after it has been rendered. The DOM API is how JavaScript is able to change content on a page.
文档对象模型(DOM)表示呈现后浏览器中的HTML。DOM API是JavaScript改变页面内容的方式。
This concept is illustrated in the following diagram:
On the initial render, React components and their JSX are no different from other template libraries. For instance, Handlebars will render a template to HTML markup as a string, which is then inserted into the browser DOM. Where React is different from libraries such as Handlebars is when data changes and we need to re-render the component. Handlebars will just rebuild the entire HTML string, the same way it did on the initial render.
在初始呈现时,React组件及其JSX与其他模板库没有什么不同。例如,Handlebars将模板作为字符串呈现为HTML标记,然后将其插入浏览器DOM中。React与Handlebars等库的不同之处在于,当数据发生变化时,我们需要重新渲染组件。Handlebars将重建整个HTML字符串,就像它在初始呈现时所做的一样。
Since this is problematic for performance, we often end up implementing imperative workarounds that manually update tiny bits of the DOM. We end up with a tangled mess of declarative templates and imperative code to handle the dynamic aspects of the UI.We don’t do this in React. This is what sets React apart from other view libraries. Components are declarative for the initial render, and they stay this way even as they’re re-rendered. It’s what React does under the hood that makes re-rendering declarative UI structures possible.React has something called the virtual DOM, which is used to keep a representation of the real DOM elements in memory. It does this so that each time we re-render a component, it can compare the new content to the content that’s already displayed on the page. Based on the difference, the virtual DOM can execute the imperative steps necessary to make the changes. So, not only do we get to keep our declarative code when we need to update the UI but React will also make sure that it’s done in a performant way. Here’s what this process looks like:
由于这对性能有问题,我们通常最终实现手动更新少量DOM的命令式解决方案。我们最终得到了一堆乱七八糟的声明性模板和命令式代码来处理UI的动态方面。在React中我们不这样做。这就是React区别于其他视图库的地方。组件在初始呈现时是声明性的,即使在重新呈现时也保持这种方式。这是React在底层所做的,使得重新渲染声明性UI结构成为可能。React有一种叫做虚拟DOM的东西,它用于在内存中保存真实DOM元素的表示。它这样做是为了每次我们重新呈现组件时,它可以将新内容与页面上已经显示的内容进行比较。基于这种差异,虚拟DOM可以执行进行更改所需的命令式步骤。当我们需要更新UI时,我们不仅会保留声明性代码React还会确保它以高性能的方式完成。这个过程是这样的:
When you read about React, you’ll often see words such as diffing and patching. Diffing means comparing old content (the previous state of the UI) with new content (the updated state) to identify the differences, much like comparing to versions of a document to see what’s changed. Patching means executing the necessary DOM operations to render the new content, ensuring that only the specific changes are made, which is crucial for performance.
当您阅读React时,您经常会看到诸如diffing和patchching之类的单词。区别意味着比较旧内容(UI的先前状态)和新内容(更新后的状态)来识别差异,这很像比较文档的版本来查看哪些地方发生了变化。修补意味着执行必要的DOM操作来呈现新内容,确保只进行特定的更改,这对性能至关重要。
As with any other JavaScript library, React is constrained by the run-tocompletion nature of the main thread. For example, if the React internals are busy diffing content and patching the DOM, the browser can’t respond to user input. As you’ll see in the last section of this chapter, changes were made to the internal rendering algorithms in React to mitigate these performance pitfalls. With performance concerns addressed, we need to make sure that we’re confident that React is flexible enough to adapt to different platforms that we might want to deploy our apps to in the future.
与任何其他JavaScript库一样,React受到主线程运行到完成特性的限制。例如,如果React内部忙于区分内容和修补DOM,浏览器就无法响应用户输入。正如你将在本章的最后一节看到的,我们对React的内部渲染算法进行了修改,以减轻这些性能缺陷。解决了性能问题后,我们需要确信React足够灵活,能够适应未来我们可能想要部署应用的不同平台。
The right level of abstraction
Another topic I want to cover at a high level before we dive into React code is abstraction.In the preceding section, you saw how JSX syntax translates to low-level operations that update our UI. A better way to look at how React translates our declarative UI components is via the fact that we don’t necessarily care what the render target is. The render target happens to be the browser DOM with React, but it isn’t restricted to the browser DOM.React has the potential to be used for any UI we want to create, on any conceivable device. We’re only just starting to see this with React Native, but the possibilities are endless. I personally will not be surprised if React Toast becomes a thing, targeting toasters that can singe the rendered output of JSX onto bread. The abstraction level with React is at the right level, and it’s in the right place.The following diagram gives you an idea of how React can target more than just the browser:
在我们深入了解React代码之前,我想在高层次上介绍的另一个主题是抽象。在上一节中,您看到了JSX语法如何转换为更新UI的低级操作。了解React如何转换声明式UI组件的一个更好的方法是,我们不必关心渲染目标是什么。渲染目标恰好是使用React的浏览器DOM,但它并不局限于浏览器DOM。React有潜力用于任何我们想要创建的UI,在任何可以想象的设备上。在React Native中,我们才刚刚开始看到这一点,但可能性是无限的。如果React Toast成为一种东西,我个人不会感到惊讶,目标是可以将JSX渲染输出烤到面包上的烤面包机。React的抽象层处于正确的级别,并且处于正确的位置。下面的图表让你了解React如何不仅仅针对浏览器:
From left to right, we have React DOM, React Native, React PDF, and React Unity. All of these React Renderer libraries, the accepts React Component and return platform specific result. As you can see, to target something new, the same pattern applies:
- Implement components specific to the target.
- Implement a React renderer that can perform the platform-specific operations under the hood.
This is, obviously, an oversimplification of what’s actually implemented for any given React environment. But the details aren’t so important to us. What’s important is that we can use our React knowledge to focus on describing the structure of our UI on any platform.Now that you understand the role of abstractions in React, let’s see what’s new in React.
显然,这是对任何给定React环境的实际实现的过度简化。但细节对我们来说并不重要。重要的是,我们可以使用React知识来专注于描述任何平台上的UI结构。既然您已经理解了抽象在React中的作用,那么让我们看看React中有什么新特性。
What’s new in React?
React is a continuously evolving library in the ever-changing web development landscape. As you embark on your journey to learn and master React, it’s important to understand the evolution of the library and its updates over time. One of the advantages of React, its core API has remained relatively stable in recent years. This provides a sense of continuity and allows developers to leverage their knowledge from previous versions. The conceptual foundation of React has remained intact, meaning that the skills acquired three or five years ago can still be applied today. Let’s take a step back and trace the history of React from its early versions to the recent. From React 0.x to React 18, numerous pivotal changes and enhancements have been made as follows:
- React 0.14: In this version, the introduction of functional components allowed developers to utilize functions as components, simplifying the creation of basic UI elements. At that time, no one knew that now we would write only functional components and almost completely abandon class-based components.
- React 15: With a new versioning scheme, the next update of React 15 brought a complete overhaul of the internal architecture, resulting in improved performance and stability.
- React 16: This version, however, stands as one of the most notable releases in React’s history. It introduced hooks, a revolutionary concept that enables developers to use state and other React features without the need for class components. Hooks make code simpler and more readable, transforming the way developers write components. We will explore a lot of hooks in this book. Additionally, React 16 introduced Fiber, a new reconciliation mechanism that significantly improved performance, especially when dealing with animations and complex UI structures.
- React 17: This version focused on updating and maintaining compatibility with previous versions. It introduced a new JSX transform system.
- React 18: This is the latest, stable release, which continues the trajectory of improvement, and emphasizes performance enhancements and additional features such as automatic batching of renders, state transitions, server components, and streaming server-side rendering. Most of the important updates related to performance will be explored in Chapter 12, High-Performance State Updates. More details about server rendering will be covered in Chapter 14, Server Rendering and Static Site Generation with React Frameworks.
React’s stability and compatibility make it a reliable library for long-term use, while the continuous updates ensure that it remains at the forefront of web and mobile development. Throughout this book, all examples will utilize the latest React API, ensuring that they remain functional and relevant in future versions. Now that we have explored the evolution and updates in React, we can delve deeper into React, and examine how to get set up with the new React project.
React的稳定性和兼容性使其成为长期使用的可靠库,而持续的更新确保它始终处于web和移动开发的最前沿。在本书中,所有的例子都将使用最新的React API,以确保它们在未来的版本中保持功能和相关性。既然我们已经探索了React的发展和更新,我们可以更深入地研究React,并研究如何设置新的React项目。
Setup a new React project
There are several ways to create a React project when you are getting started or learning. In this section, we will explore three common approaches:
- Using Web Bundlers
- Using Frameworks
- Online Code Editors
To start developing and previewing your React applications, you will first need to have Node.js installed on your computer. Node.js is a runtime environment for executing JavaScript code.
Let’s dive into each approach in the following subsections.
Using Web Bundlers
Using a web bundler is an efficient way to create React projects, especially if you are building a Single Page Application (SPA). For all of the examples in this book, we will use Vite as our web bundler. Vite is known for its remarkable speed and ease of setup and use.To set up your project using Vite, you will need to take the following steps:
- Ensure that you have Node.js installed on your computer by visiting theofficial Node.js website and downloading the appropriate version foryour operating system.
- Open your terminal or command prompt and navigate to the directorywhere you want to create your project.
- Run the following command to create a new React project with Vite:
npm create vite@latest my-vue-app -- --template vue
This command creates a new directory called my-react-app and sets up a React project using the Vite template.
Once the project is created, navigate into the project directory:
cd my-react-app
Install dependencies:
npm install
Finally, start the development server by running the followingcommand:
npm run dev
This command launches the development server, and you can view your React application by opening your browser and visiting http://localhost:3000.By now, you would have successfully set up your React project using Vite as the web bundler. For more information about Vite and possible configurations, visit the official website at https://vitejs.dev/.
Using Frameworks
For real-world and commercial projects, it is recommended to use frameworks built on top of React. These frameworks provide additional features out of the box, such as routing and asset management (images, SVG files, fonts, etc.). They also guide you in organizing your project structure effectively, as frameworks often enforce specific file organization rules. Some popular React frameworks include Next.js, Gatsby, and Remix.In Chapter 14, Server Rendering and Static Site Generation with React Frameworks, we will explore NextJS setup and some differences between using web bundlers.
对于现实世界和商业项目,建议使用构建在React之上的框架。这些框架提供了额外的开箱即用的特性,比如路由和资产管理(图像、SVG文件、字体等)。它们还指导您有效地组织项目结构,因为框架通常强制执行特定的文件组织规则。一些流行的React框架包括Next.js、Gatsby和Remix。在第14章,使用React框架的服务器渲染和静态站点生成中,我们将探索NextJS的设置以及使用web捆绑器之间的一些差异。
Online Code Editors
Online code editors combine the advantages of web bundlers and frameworks but allow you to set up your React development environment in the cloud or right inside of the browser. This eliminates the need to install anything on your machine and lets you write and explore React code directly in your browser.While there are various online code editors available, some popular options include CodeSandbox, StackBlitz, and Replit. These platforms provide a user-friendly interface and allow you to create, share, and collaborate on React projects without any local setup.To get started with an online code editor, you even don’t need an account. Try to open the link on your browser at https://react.new. In a few seconds you will see that CodeSandbox is ready to work project with live preview. To save your work, you need to create an account. Using online code editors is a convenient way to learn and experiment with React, especially if you prefer a browser-based development environment.In this section, we explored different methods for setting up your React project. Whether you choose web bundlers, frameworks, or online code editors, each approach offers its unique advantages. Select the method that you prefer and suits your project requirements, and let’s dive into the world of React development!
在线代码编辑器结合了web捆绑器和框架的优点,但允许你在云中或浏览器中设置React开发环境。这消除了在机器上安装任何东西的需要,让你可以直接在浏览器中编写和探索React代码。虽然有各种各样的在线代码编辑器可用,一些流行的选择包括CodeSandbox, StackBlitz和Replit。这些平台提供了一个用户友好的界面,允许你在没有任何本地设置的情况下创建、共享和协作React项目。要开始使用在线代码编辑器,您甚至不需要帐户。试着在https://react.new上打开浏览器上的链接。几秒钟后,您将看到CodeSandbox已准备好使用实时预览工作项目。为了保存您的工作,您需要创建一个帐户。使用在线代码编辑器是学习和实验React的一种方便的方式,特别是如果你喜欢基于浏览器的开发环境。在本节中,我们探讨了设置React项目的不同方法。无论您选择web捆绑器、框架还是在线代码编辑器,每种方法都有其独特的优势。选择您喜欢且适合您的项目需求的方法,让我们深入React开发的世界!
Summary
In this chapter, you were introduced to React at a high level. React is a library with a small API used to build UIs. Next, you were introduced to some of the key concepts of React. We discussed the fact that React is simple because it doesn’t have a lot of moving parts. Afterward, we explored the declarative nature of React components and JSX. Following that, you learned that React takes performance seriously, enabling us to write declarative code that can be re-rendered repeatedly. You also gained insight into the idea of render targets and how React can easily become the UI tool of choice for all of them. I then provided you with a brief overview of React’s history and introduced latest developments. Finally, we delved into how to set up a new React project and initiate the learning process.That’s sufficient introductory and conceptual content for now. As we progress through the book’s journey, we’ll revisit these concepts. Next, let’s take a step back and nail down the basics, starting with JSX in the next chapter.
在本章中,我们向您介绍了React的基本知识。React是一个带有小型API的库,用于构建ui。接下来,向您介绍了React的一些关键概念。我们讨论了React简单的事实,因为它没有很多可移动的部分。之后,我们探讨了React组件和JSX的声明性。在此之后,您了解到React非常重视性能,使我们能够编写可重复呈现的声明性代码。您还深入了解了渲染目标的概念,以及React如何轻松地成为所有渲染目标的首选UI工具。然后我向您简要介绍了React的历史,并介绍了最新的开发。最后,我们深入研究了如何建立一个新的React项目并启动学习过程。到目前为止,这是足够的介绍性和概念性内容。随着本书的进展,我们将重新审视这些概念。接下来,让我们后退一步,确定基础知识,从下一章的JSX开始。