Conclusion chat | React 17, talk about learning the front frame of art

Through previous learning, we have also established a systematic and in-depth understanding of React from the basics to principles and production practices. React 17 was released recently, but many people may be confused about what React 17 actually means. So, for the final installment of this column, let’s talk about the future of React — and the changes that the React 17 version brings. Then we talk about future-oriented learning — it’s better to teach people how to fish than to teach them how to fish, and how do we ensure that we remain alert and able to understand new things as front-end frameworks change and technology changes? Finally, we will make an extraction of the learning methodology of the front-end framework, hoping that we can establish good learning habits.

1. React 17 has changed things

React 17 React 17

  • The React V17 release is unusual because it doesn’t add any new features for developers. However, this version will make upgrading React itself much easier.

In particular, React V17 serves as a “cornerstone” for subsequent releases, making it easier for different versions of React to nest with each other. – the React official

There are no new features in React 17, due to its orientation. React v17 is intended to be the “cornerstone” for subsequent React releases 18 and 19. It will be a “bridge between the past and the past”, and in the official words, “React V17 opens a new chapter in the evolution of React”.

The so-called “incremental upgrade” is as opposed to “one-time upgrade”. When you migrate a project from React 17 to newer versions 18, 19, etc., you don’t need to upgrade the entire application to the new version at once, but you can upgrade parts of the application. For example, you can safely introduce a component from React 17 in React 18. Prior to React 17, there was a risk of unavailability, where upgrading the React version required migrating the entire application to the target version at once.

The “incremental upgrade” means more options, and it will make room for a lot of older React projects in the future, ensuring developers don’t have to worry too much about being compatible with multiple versions.

Just because there’s no new feature doesn’t mean there’s no change, and it doesn’t mean there’s nothing left to learn. In fact, React 17 still has a number of user-side changes to watch, but I think the most important ones are the following:

  • New JSX transformation logic

  • Event System Refactoring

  • Introduction of Lane model

React 17 also has a number of detailed changes, such as adjusting the timing of the useEffect hook to clear side effects, and enhancing the error check for components returning undefined. These are also interesting changes that you can explore at your own time.

1. Refactor the JSX transformation logic

In the past, we would have written code like this in a React project:

Function MyComponent() {return <p>Copy the code

React generates an error because conversions to JSX code in React rely on the React. CreateElement function. So whenever you include JSX in your code, you must introduce React in your files, like this:

import React from 'react'; Function MyComponent() {return <p>Copy the code

React 17 allows direct use of JSX without introducing React. This is because in React 17, the compiler automatically imports the JSX parser for us, which means something like this:

Function MyComponent() {return <p>Copy the code

The compiler converts it to something like this:

import {jsx as _jsx} from 'react/jsx-runtime'; Function MyComponent() {return _jsx('p', {children: 'this is MyComponent'}); }Copy the code

The react/ JsX-Runtime JSX parser replaces the React. CreateElement compiler for JSX, which is automated and insensitive to developers. Therefore, the most significant change brought about by the new JSX transformation logic is the reduced learning cost for developers.

Why lower the cost of learning? Remember, when getting started with React, was it easy to miss the introduction of React and cause JSX-related problems? When these problems occur, it is hard to avoid being confused as a novice. When you become an advanced player and understand the relationship between JSX and React. CreateElement, you’ll know the truth that JSX must be introduced with React forever. So every time you use JSX, you have to manually import React. Although it is extremely inconvenient, there is nothing you can do about it.

However, if you learn React 17, you will not realize that React needs to be introduced with JSX from the beginning, and you will not have to worry about the many reasons behind it. React 17 already takes care of everything for you.

The new JSX transformation logic tells us that frameworks are not necessarily more complex and more difficult to learn. A good framework, or even a good “wheel,” is always about simplicity and stability.

The react/ jsx-Runtime JSX parser doesn’t look very different from the react. CreateElement parser. Of course not, it internally optimizes and simplifies performance in ways that react.CreateElement can’t. In some cases, it may slightly improve the size of the compiled output.

2. Event system reconstruction

Refactoring the event system in React 17 takes two aspects:

  • Remove the burden of history

  • Embrace new trends

1). Remove historical burden: give up using document to do the centralized control of events

In Lecture 18 of this column, we took a closer look at the implementation of the event system in the React 16.13.x version. It was repeatedly emphasized at the time that React would implement centralized control of events by bubbling all events into documents.

This may seem clever enough, but it’s still not clever enough — document is the root of the document tree, and the impact of manipulating document is just too large, which makes things even more out of control. The most famous of these is the GitHub issue below:

The questioner said he tried to prevent bubbling in the React event function on the input element, but it didn’t work — every time input was clicked, the event would still bubble up to the document. To which he received this reply:

The reason is the same as you’d expect: React relies on bubbling DOM events into documents to achieve centralized control over all events. In the source code, the author blocks bubbles in the React event function handleClick. This only ensures that the resultant event is prevented from bubbling in the React event system. The source level analysis in Lecture 18 does not prevent native DOM events from bubbling up. So the event listener installed on the Document must be fired.

Apart from the document centralized control of the setting to the developers how much restrictions, just look at the design concept, how much can predict the risk: Document is a global concept, and the component is only a part of the global. The React event system, introduced by the React component, is ideally tied to components and should not extend the impact to the whole world.

In React 17, the React team finally addressed this issue head-on: centralized event management was no longer entirely document dependent, and the logic related to event management was moved to the DOM node of each React component’s container. For example, mount a React component under a DOM node with ID root like this:

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Copy the code

The event control logic is installed on the root node. This way, the React component can play on its own and no longer pose a threat to the global event flow.

2). Embrace the new trend: ditch event pools

Before React 17, synthesized event objects were managed centrally in a place called an event pool. The purpose of this is to enable reuse of event objects, which in turn improves performance: every time an event handler completes execution, all properties within its corresponding composite event object are empty in preparation for reuse. This means that once the React logic is executed, the event object cannot be retrieved.

function handleChange(e) {
  // This won't work because the event object gets reused.
  setTimeout(() => {
    console.log(e.target.value); // Too late!
  }, 100);
}
Copy the code

The setTimeout callback is executed asynchronously after the handleChange handler completes, so it can’t get the desired event object e.

Many of us have had the experience of writing a Bug because we couldn’t get the event object we wanted. The event pool design, while good for performance, is confusing to users. Many people realize in hindsight, only after writing countless bugs, that to get to the target event object, they must explicitly tell React — I always need it, which is to call the e.pineist () function, like this:

function handleChange(e) {
  // Prevents React from resetting its properties:
  e.persist();
  setTimeout(() => {
    console.log(e.target.value); // Works
  }, 100);
}
Copy the code

In older versions, React did this in large part to provide backward compatibility with older browsers that were not performing as well.

But as times have changed, the browsers on the market today, while not perfect, rarely show you a memory leak just because there are too many objects in the event pool. So React 17 embraced the new-age trend of re-choosing between the r&d experience and backward compatibility performance, and this time it opted for the former — ditching event pools and creating new objects for each synthesized event.

In React 17, you can access event objects whenever and wherever you want without using e.pineist ().

3. Introduction of Lane model

If you’ve ever tried to follow and read the React source code for a sustained period of time, you’ll find that almost every minor update in React 16 involves moving the Fiber Reconciler logic. This point often makes people feel sad: “There’s another change, I can’t finish, I can’t finish…” . Although the changes are only at the coding level and do not affect the core ideas, they can still be quite stressful for learners of source code.

To avoid a similar dilemma, this column covers several lectures (nos. 14-17) of the Fiber source code, all of which are drawn from React 17 — going straight to the latest is the safest bet at the moment, which means we’ve captured the React team’s “best thinking” so far.

In the analysis of lectures 14 to 17, we have actually seen the concept of “Lane” in various corners of the source code, and analyzed some of the lan-related functions. As a result, it may be natural for newcomers to React source code to think that priority should be handled with lanes. In fact, React 16 deals with priorities using the expirationTime model.

The expirationTime model uses a expirationTime (a length of time) to describe the priority of a task; The Lane model uses binary numbers to represent the priority of tasks:

  • The Lane model * operates on the priority ** through a 31-bit bit operation by assigning different priorities to a single bit.

  • Lane model provides a new priority sorting idea. Compared with expirationTime, it has a more delicate priority processing and can cover more boundary conditions.

4. How to gain insight into a front-end framework

As front-end personnel, it is inevitable to understand and learn a strange front-end framework, so in the face of a strange front-end framework, how to efficiently and smoothly complete the transformation from “small worker” to “expert”?

Of course, there is no standard answer to this question, which is related to everyone’s learning habits, learning efficiency and even metacognitive ability. But there are behavioral rules that can be reused. So here are some proven, actionable learning experiences that you may learn from and that will help you later in your career.

1) Don’t underestimate official documents

In the actual reader survey, it was found that many people did not pay enough attention to React official documents. People get used to getting “up and running” with documentation at the beginning stage, but they don’t get to see the more valuable information that documentation can give us — the framework’s design ideas, the source code layering, and the introduction of special feature points.

The React document is an excellent example of a front-end framework document. If you know how to use the document, you will find that it is not just an API manual or an introductory tutorial, but a set of official instructions.

If the summary of some of the documents in this column is useful to you, try reading the full text. In daily source code reading, including production practice, if you encounter problems with React, don’t rush to read spotty community articles — try the React documentation first, and you may learn more than you think.

2) Call stack is your learning map

If you’ve gone beyond reading official documentation, then you might want to know how the framework actually works. At this point, you have the framework’s design concepts and basic features, and some hands-on experience with simple projects, but you may not have the knowledge or mental preparation to challenge the source code from scratch. At this point, the framework’s function call stack will give you a lot of directional questions before you read the source code.

For example, if you want to learn about Hooks, try looking at the function call stack triggered by the different Hooks calls and find the functions that are most visible, which most likely indicate the main flow of Hooks source code. The same goes for event systems, render procedures, etc. Looking at the call stack, looking for commonalities, and then peer-to-peer reading of the source code for key functions makes it much easier to read the source code.

3) How to read the source code

Once you understand the source logic for some of the core features, it’s hard not to wonder how the framework works as a whole. It is still not a wise choice to read all the source code directly from the entry file.

Before reading the source code, the whole framework to review the official best architecture framework design, introduces related source layer, the information may not be fully exposed in the document, but always with the help of a search engine can find some clues, such as framework, the author/official team blog, the content of authority about the same as the document.

After understanding the architectural layers of the entire framework project, you can read the source code in a variety of ways: you can try to read layers, figure out one big problem at a time, and finally put the whole idea together according to the logic of the architectural layers; You can also use the call stack to map each level of logic by looking at the functions involved in a complete execution process (such as the React first-screen rendering process) and then split it down, depending on the individual.

5, summary

This concludes our exploration of the React world.

I hope you will not only gain a clear understanding of the React framework, but also a healthy and sustainable methodology for front-end learning.

After several years of competition and precipitation, the stability of the mainstream front-end frameworks has gradually strengthened, and all three frameworks are evolving towards the standard of Web Components, not tending to disorder, but becoming more and more certain and predictable. Therefore, there is no need to be superstitious in the public opinion of “not finished learning” this kind of anxiety rendering, let alone blindly chasing new tricks. In this current trend, many times if you can deeply understand a good framework, you can quickly accumulate a lot of reusable understanding experience, which will create a great acceleration of learning other new knowledge.

So take your time. Maybe it’ll be faster.

The mainstream frameworks tend to stabilize, while the front-end world continues to thrive. In recent years, new concepts such as Serverless, low code, intelligence, and cross-platform have emerged one after another, each of which is enough to push the front end into a new era. In the face of endless technical hot spots, we should not only keep a cool head, but also keep a fast pace. All of these, you need to take the initiative to build and continue to iterate their own effective learning habits. [Note] This column of handling also formally came to an end, so as this column of porters, but also this column of learners, after learning this column, feel benefited a lot, of course, also retained doubts in the heart, for the knowledge of learning did not learn through. It can be seen that module two knowledge points are more, the length is also larger, so to really understand these knowledge points, only to learn once is certainly not enough, so they also have to continue to knowledge points over several times, seriously and seriously study, and try to work hard

6, the appendix

To study the source