- What’s New in React 16 and Fiber Explanation
- By Trey Huffine
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: yoyoyohamapi
- Proofread by Tina92 Sunui
What does React 16 bring and explain Fiber
Feature Overview — The much-anticipated React 16
The React core algorithm has been updated for years – this update provides a basic rewrite of the React Reconciliation algorithm. The Reconciliation algorithm is used by React to compare the differences between two DOM trees to determine which part should be updated. React will maintain the same public API and allow most projects to upgrade immediately (assuming you’ve fixed the deprecation warnings). A new version is released for the following purposes:
-
The ability to break up interruptible work in the rendering process into chunks.
-
Provides prioritization, rebase, and reuse capabilities for work in the rendering process.
-
The ability to easily switch between parent and child components in the rendering process makes it possible to implement layout in React.
-
Ability to return multiple elements from the Render () function.
-
Better support for Error Boundary.
-
** can follow me on GitConnected >**
features
Core algorithm rewriting
The main feature of this algorithm rewrite is asynchronous rendering. (Note: not yet supported in 16.0, but will be an optional feature in a future 16.x release). In addition, the new rewrite removes some of the immature abstractions that prevented internal change.
Much of this comes from Lin Clark’s talk, so you can support her unique overview by checking out this talk and following and liking Clark on Twitter.
The beauty of asynchronous rendering is the ability to divide the rendering task into multiple chunks. The browser’s rendering engine is single-threaded, which means that almost all behavior happens synchronously. React 16 manages the main thread and rendering process by using a native browser API to intermittently check if there are other tasks that need to be done. In Firefox, an example of a browser main thread is simple:
while(! mExiting) { NS_ProcessNextEvent(thread); }Copy the code
In previous versions React would lock the entire thread while evaluating the DOM tree. This reconciliation process is now called stack Reconciliation. Although React is known for being fast, locking entire threads can cause some applications to run less smoothly. This version fixes this problem by not requiring the rendering process to complete once after initialization. React evaluates a portion of the DOM tree and then pauses rendering to see if the main thread has any drawing or updates that need to be done. Once drawing and updating is complete, React will continue rendering. This process is accomplished by introducing a new data structure called “Fiber.” Fiber maps to a React instance and manages its rendering tasks for that instance, which also knows how it relates to other Fibers. A fiber is just a JavaScript object. The image below compares the old and new rendering methods.
React 16 also manages the priorities of individual updates when necessary. This allows high-priority updates to be processed first at the beginning of the queue. An example of this is keystroke input. For the sake of application fluency, the user needs an immediate keystroke response, so keystroke input has a higher priority than lower-priority update tasks that can wait 100-200 milliseconds.
The user experience is improved by breaking up UI updates into small units of work. The reconciliation task is paused to allow the main thread to perform other urgent tasks, which provides a smoother interface and a perceived performance improvement.
Error handling
In React, errors were always difficult to handle, but with React 16, everything changed. Errors that occurred inside components in previous versions would contaminate the React state and cause more ambiguous errors in subsequent renderings.
React 16 contains Error Boundary that not only provides clear error messages, but also prevents the entire application from crashing due to errors. When error Boundary is added to your application, it catches errors and displays a corresponding UI without crashing the entire component tree. Boundary can catch errors in the rendering period of the component, in the lifecycle method, and in the construction of all its subtrees. Error Boundary is easily implemented with a new lifecycle method componentDidCatch(Error, INFO).
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display a fallback UI
this.setState({ hasError: true });
// You can also export error logs to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>Copy the code
In this example, any errors that occur in
component. This functionality is similar to the Catch {} block in JavaScript. If Error Boundary receives an error state, you as the developer can determine what UI to display at that point. Note that error boundary only catches the errors of its children, but does not identify its own errors.
Further, you can see the following sound, controllable error messages:
compatibility
Asynchronous rendering
The initial release of React 16.0 will focus on compatibility with existing applications. Asynchronous rendering will no longer be optional at first, but will be an optional feature in future 16.x releases.
Browser compatibility
React 16 relies on maps and sets. To ensure compatibility with all browsers, you need to introduce related Polyfills. The current popular polyfill is available in core-JS or Babel-Polyfill.
React 16 also relies on requestAnimationFrame, which is used primarily for testing. A SHIM for testing purposes could be:
global.requestAnimationFrame = function(callback) {
setTimeout(callback);
};Copy the code
Component declaration cycle
Because React implements priority Settings for rendering, you can no longer be sure that componentWillUpdate and shouldComponentUpdate of different components will be called in the expected order. The React team is currently working on providing an update path to prevent these applications from being affected by the above behavior.
use
React 16 is currently in beta as of this article, but it will be released soon. You can try React 16 in the following ways:
# yarn
yarn add react@next react-dom@next
# npm
npm install --save react@next react-dom@nextCopy the code
If you find this article useful to you, please send me a 👏. Follow me on Medium where you can read more about React, nonde.js, JavaScript, and open source software. You can also find me on Twitter or GitConnected. Gitconnected – a community of software developers and engineers. Create an account and log in to GitConnected, one of the largest communication communities for developers today. Here’s its latest address, gitConnected.com
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, React, front-end, back-end, product, design and other fields. If you want to see more high-quality translation, please continue to pay attention to the Project, official Weibo, Zhihu column.