We are very excited to announce React V16.0! These changes include a number of long-standing features, including fragments, error boundaries, portals, support for custom DOM attributes, enhancements to [server-side rendering], and reduced library size.

New render return types: fragments and strings

You can now return an array of elements from the component’s render method. Similar to other arrays, but you need to add a key to each element to avoid warnings:


      
render() {
  // No need to wrap list items in an extra element!
  return [
    // Don't forget the keys :)
    <li key="A">First item</li>,
    <li key="B">Second item</li>,
    <li key="C">Third item</li>,
  ];
}


      Copy the code

In the future, we will most likely add a special shard syntax to JSX that doesn’t require a key.

We also added support for return strings:

render() { return 'Look ma, no spans! '; }Copy the code

See the complete list of supported return types.

Better error handling

Previously, a render runtime error would put React in an error state, generating an encrypted error message and requiring a page refresh. React 16 uses a more flexible error handling strategy to deal with this problem. By default, if an error is thrown in a render or lifecycle method within a component, the entire component is not rendered from the root. This prevents error messages from being displayed. However, it may not be the ideal user experience.

Instead of uninstalling the entire application every time an error occurs, you can use error boundaries. Error boundaries are special components used to catch errors within a subtree and display the fallback UI in their place. You can think of error boundaries as similar to try-catch statements, but for React components.

For more details, check out our previous article on React 16 error handling.

Portals

Portals provide an excellent way to render child nodes to DOM nodes other than the parent component.


      
render() {
  // React does *not* create a new div. It renders the children into `domNode`.
  // `domNode` is any valid DOM node, regardless of its location in the DOM.
  return ReactDOM.createPortal(
    this.props.children,
    domNode,
  );
}


      Copy the code

You can see an example of this in the documentation on Portals.

Better server-side rendering

React 16 includes a completely rewritten server renderer. It’s really fast. Streaming is supported, so you can send data to clients faster. And process.env is no longer checked for compilation due to the new packaging policy (believe it or not, reading process.env from Node is really slow!). You no longer need to package React to get good server-side rendering performance.

Core team member Sasha Aickin wrote a nice post describing the improvements to render on the React 16 server. According to Sasha’s comprehensive benchmarks, React 16 rendered servers about three times faster than React 15. “Approximately 2.4x performance improvement under Node 4, 3.x performance improvement under Node 6, and 3.8x performance improvement under the newly released Node 8.4 compared to React 15 compiled with Process. env. When compared to uncompiled React 15, React 16 has an entire order of magnitude gain in server rendering on the latest versions of Node!” (As Sasha points out, please note that these numbers are based on comprehensive benchmarks and don’t necessarily reflect true performance.)

Also, React 16 is better at preserving HTML on the server side once it reaches the client. It no longer requires that the initial render match exactly the render result of the server. Instead, it tries to reuse existing DOM elements as much as possible. No longer checksums! In general, we don’t recommend rendering different content on the client side than on the server side, but it can be useful in some cases (e.g., timestamps).

See the documentation on ReactDOMServer for more details.

Support for custom DOM attributes

React now passes custom attributes to the DOM, rather than ignoring HTML and SVG attributes that it doesn’t recognize. This enabled us to eliminate the need to whitelist the React feature in maintenance and was able to reduce file size.

Reduce file size

React 16 is actually less than 15.6.1!

  • reactReduced from 20.7 KB (after GZIP: 6.9 KB) to 5.3 KB (after GZIP: 2.2 KB).
  • react-domReduced from 141 KB (post-GZIP: 42.9 KB) to 103.7 KB (post-GZIP: 32.6 KB).
  • react + react-domReduced from 161.7 KB (post-GZIP: 49.8 KB) to 109 KB (post-GZIP: 34.8 KB)

Combined, the two are 32% smaller than the previous version (30% after GZIP).

The volume difference is mainly due to the change of packages. React now uses Rollup for flat packaging to handle different target formats, which results in both volume and performance improvements. The flat package format also means React has roughly the same impact on package size no matter how you run your application, whether using Webpack, Browserify, pre-built UMD packages or other systems.

MIT agreement

In case you missed it, React 16 uses the MIT protocol. We also released React 15.6.2 under the MIT protocol for those who can’t upgrade right away.

New Core Architecture

React 16 was the first release to feature a new core architecture from the top, codenamed “Fiber.” You can read about the project on Facebook’s engineering blog. (Spoiler: We rewrote React!)

Fiber is responsible for most of the new features in React 16, such as error boundaries and fragments. In the next few releases, you can expect us to unlock more of React’s potential features.

Probably the most exciting area of our work right now is asynchronous rendering – a strategy that periodically performs scheduled rendering work on the browser. The result is that with asynchronous rendering, applications respond better because React avoids blocking the main thread.

This example provides a preview of some of the problems that asynchronous rendering can solve:

Have you considered what “asynchronous rendering” is? Here is a Demo that shows how to coordinate asynchronous React tree work without React. t.co/3snoahB3uV pic.twitter.com/egQ988gBjR

– Andrew Clark (@ acdlite)
September 18, 2017

Tip: Watch out for the rotating black square.

We think asynchronous rendering is a big move and represents the future of React. In order to make the migration to V16.0 as smooth as possible, we still don’t support asynchronous features, but we look forward to rolling them out in the coming months. Stay tuned!

The installation

React V16.0.0 can be installed using NPM.

Install React 16 using Yarn. Run the following command:

Yarn add react @ ^ 16.0.0 react - dom @ ^ 16.0.0Copy the code

Install React 16 using NPM.

NPM install --save react@^16.0.0 react-dom@^16.0.0Copy the code

We also provide UMD built React via CDN:


      
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>


      Copy the code

See the documentation for details on installation instructions.

upgrade

Although React 16 includes significant internal changes, in terms of upgrades, you could argue that this is similar to other major React releases. We’ve been using React 16 for Facebook and Messenger.com users since earlier this year, and we’ve released several beta releases and patches to address additional issues. Minor exceptions aside, if your application is running on 15.6 with no warning, it should also work under 16.

In the new

Containers that retain server-side rendering for Hydrating now have clearer API definitions. If you want to reuse server-side HTML, use reactdom.hydrate instead of reactdom.render. If you just want to do client render, continue to use reactdom.render.

React Add-on suite

As previously announced, we are no longer adding support for React Addons. We expect every add-on suite (except react-Addons-perf; Before viewing) will continue to work for the foreseeable future, but we will not be releasing additional updates.

Refer to the previous blog for advice on how to migrate.

React -addons-perf does not work in React 16. We may release a new version of the tool at a later date. In the meantime, you can use your browser performance tool to measure the React component.

update

React 16 includes a number of small changes. These changes will only affect a few infrequently used examples, and we don’t expect them to interfere with most applications.

  • React 15 is in useunstable_handleErrorHas been restricted to no longer providing documentation support for error boundaries. The method has been renamed tocomponentDidCatch. You can use codemod to do thisAutomatically migrate code to the new API.
  • If called inside a lifecycle methodReactDOM.renderReactDOM.unstable_renderIntoContainer, it returns null. To keep it working, you can use itportals 或 refs.
  • setState:
    • Call through NULLsetStateUpdates are no longer triggered. This allows you to determine if you want to re-render in the update function.
    • Called in the Render methodsetStateUpdates are triggered. This is different than before. Anyway, you should not call setState in render.
    • setStateThe callback function (second argument) will now be incomponentDidMount / componentDidUpdateTrigger immediately instead of waiting until all components have been rendered.
  • When using<B />To replace<A />.B.componentWillMountNow in theA.componentWillUnmountBefore triggering. Before, in some cases,A.componentWillUnmountIt triggers immediately.
  • Previously, changing a reference to a component always resulted in dereferencing the component before rendering. Now when modifying a DOM node, we put the reference adjustment behind.
  • Rerendering to a container that wasn’t modified by React isn’t safe. This worked in some cases before but React no longer supports it. Now we will trigger a warning in this case. You should clean up the use in your component treeReactDOM.unmountComponentAtNodeThe component.Take a look at this example.
  • componentDidUpdateLifecycle methods are no longer passedprevContextParameters. (see the# 8631)
  • Shallow renderers are no longer calledcomponentDidUpdateBecause DOM references are not available. This also andcomponentDidMountBe consistent (previous versions will not call eithercomponentDidMount).
  • Shallow renderers are no longer implementedunstable_batchedUpdates

package

  • There is no longerreact/lib/*react-dom/lib/*. React and ReactDOM are precompiled as single files (” flat bundles “) even in the CommonJS environment. If you relied on the React internal methods that were not documented, they are no longer valid. You can explain your situation in a new issue and we will advise you on migration as much as possible.
  • There is no longerreact-with-addons.jsBuild a package. All compatible add-ons are released separately on NPM, or in a single-file browser version if desired.
  • Deprecations introduced in 15.x have been removed from the core package.React.createClassavailablecreate-react-classInstead,React.PropTypesprop-typesInstead,react-dom-factoriesTo take the place ofReact.DOM.react-dom/test-utilsTo take the place ofreact-addons-test-utilsAs well as shallow renderers availablereact-test-renderer/shallow. To view15.5.0 和 15.6.0For advice on code migration and Automated Code Modification (Codemods).
  • The single-file browser build names and paths have been adjusted to highlight the differences between the development and production builds. Such as:

    • react/dist/react.jsreact/umd/react.development.js
    • react/dist/react.min.jsreact/umd/react.production.min.js
    • react-dom/dist/react-dom.jsreact-dom/umd/react-dom.development.js
    • react-dom/dist/react-dom.minThe.js –react-dom/umd/react-dom.production.min.js

JavaScript Environment Requirements

React 16 relies on the Set types Map and Set. If you want to support older browsers and devices that may not have native support (IE < 11, for example), consider including a global polyfill in your app library, such as core-js or babel-Polyfill.

A React 16 Polyfill environment with core-JS support for older browsers looks like this:

import 'core-js/es6/map'; import 'core-js/es6/set'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hello, world! </h1>, document.getElementById('root') );Copy the code

React also relies on the requestAnimationFrame (even the test environment). A simple SHIM in a test environment looks like this:


      
global.requestAnimationFrame = function(callback) {
  setTimeout(callback, 0);
};


      Copy the code

Thank you

As always, this release would not be completed without contributions from the open source community. Thanks to everyone who contributed bugs, PR, questions, documentation, and more!

Special thanks to our core contributors, especially for their outstanding contributions during the pre-release cycle over the past few weeks: Brandon Dail, Jason Quense, Nathan Hunzaker, and Sasha Aickin.

Edit this page