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開始。