render() {
return 'Look ma, no spans!';
}
See the full list of supported return types.
Better error handling
エラー・ハンドリングの改善
Previously, runtime errors during rendering could put React in a broken state, producing cryptic error messages and requiring a page refresh to recover. To address this problem, React 16 uses a more resilient error-handling strategy. By default, if an error is thrown inside a component’s render or lifecycle methods, the whole component tree is unmounted from the root. This prevents the display of corrupted data. However, it’s probably not the ideal user experience.
以前は、レンダリング時にランタイム・エラーが生じた場合、React は壊れた状態になってしまい、意味不明なエラー・メッセージを表示していました。そしてその状態を直すためにはページを再更新する必要がありました。 このような問題に対処するため、React 16 はより柔軟性のあるエラーハンドリング戦略を用いることにしました。初期設定では、エラーがコンポーネントの render メソッドやライフサイクル・メソッドの中で生じた場合、コンポーネント・ツリー全体が、ルートコンポーネントからアンマウントされるようになっています。これによって、壊れたデータが表示されることを防いでいます。しかし、おそらくこれは、理想的なユーザー体験とは言い難いものです。
Instead of unmounting the whole app every time there’s an error, you can use error boundaries. Error boundaries are special components that capture errors inside their subtree and display a fallback UI in its place. Think of error boundaries like try-catch statements, but for React components.
エラーが生じる度にアプリケーション全体をアンマウントするのではなく、代わりに「Error Boundaries」を用いることができます。「Error boundaries」は、特別なコンポーネントで、自身の下層にあるツリーで生じたエラーを捉えて、フォールバック UI を代わりに表示します。「Error boundaries」は、トライ/キャッチ文と同じようなものだと考えてもいいでしょう。ただし React コンポーネントのためのトライ/キャッチ文です。
For more details, check out our previous post on error handling in React 16.
詳細は previous post on error handling in React 16 を確認ください。
Portals
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
「portal」機能は、子要素を、親コンポーネントのDOMヒエラルキーの外側に存在するDOM node に対して、レンダリングする機能です。
render() {
return ReactDOM.createPortal(
this.props.children,
domNode,
);
}
See a full example in the documentation for portals.
(訳注: react は通常、自分の子要素の位置にコンポーネントをレンダリングするが、portal を用いると、その縛りから放たれて、どの DOM に対してもコンポーネントをレンダリングをできるようだ。具体的なユースケースとして、overflow: hidden されている親要素の中のコンポーネントから、モーダルウィンドウを生成したい場合があげられている。通常であれば、overflow: hidden されている要素の子要素として DOM がレンダリングされる以上、親要素の外にはみ出るような視覚表現を作り出すことができない。このような条件において、親要素の外側に DOM をレンダリングする必要が発生し、その場合に portal 機能が有用となる。)
Better server-side rendering
サーバーサイドレンダリングの改善
React 16 includes a completely rewritten server renderer. It’s really fast. It supports streaming, so you can start sending bytes to the client faster. And thanks to a new packaging strategy that compiles away process.env
checks (Believe it or not, reading process.env
in Node is really slow!), you no longer need to bundle React to get good server-rendering performance.
React 16 は、完全に新たに書き直された server render を用いています。これによって非常に早くなりました。この新しい server render は、ストリーミングをサポートしており、非常に早くクライアントへの情報送信を開始することができるようになりました。また new packaging strategy のお陰で(これはprocess.env のチェックをコンパイルから取り除いています。信じられないかもしれませんが、Node の process.env は本当に遅いのです!)、サーバーレンダリングのパフォーマンスをよくするためにReact をバンドルする、ということが必要なくなりました。
Core team member Sasha Aickin wrote a great article describing React 16’s SSR improvements. According to Sasha’s synthetic benchmarks, server rendering in React 16 is roughly three times faster than React 15. “When comparing against React 15 with process.env
compiled out, there’s about a 2.4x improvement in Node 4, about a 3x performance improvement in Node 6, and a full 3.8x improvement in the new Node 8.4 release. And if you compare against React 15 without compilation, React 16 has a full order of magnitude gain in SSR in the latest version of Node!” (As Sasha points out, please be aware that these numbers are based on synthetic benchmarks and may not reflect real-world performance.)
React 開発のコアメンバーである「Sasha Aickin」がRact 16 の SSR が大きく進歩したということについて記事を書いています。「great article describing React 16’s SSR improvements」 Sahsa のシンセティック・ベンチマークによればReact 16 のサーバーレンダリングは、ざっくりって React 15 の3倍は早いことがわかりました。「process.env をコンパイルした React15 と比較すると、node 4 では2.4倍の改善がされ、node 6 では3倍の、そして最新のnode 8.4 では3.8倍の改善がされました。そしてコンパイルなしの react 15 と比較するとすれば、最新バージョンの Node では、なんと一桁違う改善がされています!」(Sashaが指摘していることですが、この数字はシンセティック・ベンチマークによるもので、実際のパフオーマンスを、必ずしも反映するものではない点に注意してください。)
In addition, React 16 is better at hydrating server-rendered HTML once it reaches the client. It no longer requires the initial render to exactly match the result from the server. Instead, it will attempt to reuse as much of the existing DOM as possible. No more checksums! In general, we don’t recommend that you render different content on the client versus the server, but it can be useful in some cases (e.g. timestamps).
加えて、React 16 は hydrating server-rendered HTML を改善しています。(ただし一旦クライアントにリーチした場合のみですが) 最早、サーバーからの結果と完全にマッチさせるために最初のレンダリングをする、という必要がなくなりました。その代わりに、既に存在するDOMを最大限、再活用するようになりました。もうチェックサムは必要ありません!一般的に言って、クライアント側とサーバー側で異なるコンテンツをレンダリングすることは、おすすめしません。とはいえ有効なケースもあります。(例えばtimestampなど)
See the documentation for ReactDOMServer
for more details.
Support for custom DOM attributes
カスタム DOM 属性のサポート
Instead of ignoring unrecognized HTML and SVG attributes, React will now pass them through to the DOM. This has the added benefit of allowing us to get rid of most of React’s attribute whitelist, resulting in reduced file sizes.
HTML と SVG の React が認識できない属性に関して、今まで React は無視をしてきましたが、React 16 ではそのまま DOM に渡すようになりました。これによって以前のReactのホワイト・リストを使わなくて良くなるので、結果としてファイルサイズが小さくなります。
Reduced file size
小さくなったファイルサイズ
Despite all these additions, React 16 is actually smaller compared to 15.6.1!
様々な機能追加にもかかわらず、React 16 は 15.6.1 よりもファイルサイズが小さくなりました!
react
is 5.3 kb (2.2 kb gzipped), down from 20.7 kb (6.9 kb gzipped).
react-dom
is 103.7 kb (32.6 kb gzipped), down from 141 kb (42.9 kb gzipped).
react
+ react-dom
is 109 kb (34.8 kb gzipped), down from 161.7 kb (49.8 kb gzipped).
That amounts to a combined 32% size decrease compared to the previous version (30% post-gzip).
The size difference is partly attributable to a change in packaging. React now uses Rollup to create flat bundles for each of its different target formats, resulting in both size and runtime performance wins. The flat bundle format also means that React’s impact on bundle size is roughly consistent regardless of how you ship your app, whether it’s with Webpack, Browserify, the pre-built UMD bundles, or any other system.
サイスが小さくなった理由の一部は、packaging 方法の変更にあります。React は Rollup を用い、異なった対象のフォーマットへのフラットバンドルを作っています。結果としてサイズの点でもランタイム・パフォーマンスの点でも向上しました。フラットバンドルフォーマットであるということは同時に次のことも意味します。つまり、Webpack, Browserify, the pre-built UMD bundles, や他のどのシステムを用いてアプリケーションを最終的にバンドルするとしても、Reactのバンドルサイズは小さいままです。
MIT licensed
In case you missed it, React 16 is available under the MIT license. We’ve also published React 15.6.2 under MIT, for those who are unable to upgrade immediately.
React 16 は MIT ライセンスで運用されます。15.6.2 も同じく MIT ライセンスでした。
New core architecture
新しいコア・アーキテクチャ
React 16 is the first version of React built on top of a new core architecture, codenamed “Fiber.” You can read all about this project over on Facebook’s engineering blog. (Spoiler: we rewrote React!)
React 16 は新しいコアアーキテクチャである”Fiber”のもと構築された、最初のReact です。このプロジェクトの全貌については Facebook’s engineering blog の記事で知ることができます。
Fiber is responsible for most of the new features in React 16, like error boundaries and fragments. Over the next few releases, you can expect more new features as we begin to unlock the full potential of React.
“Fiber” こそが、React 16 の新機能の多くの立役者です。error boundaries や fragment といった新機能は Fiber によって成り立っています。次に続くいくつかのリリースでも、さらに多くの新機能を追加する予定です。React のポテンシャルを最大限引き出していきます。
Perhaps the most exciting area we’re working on is async rendering—a strategy for cooperatively scheduling rendering work by periodically yielding execution to the browser. The upshot is that, with async rendering, apps are more responsive because React avoids blocking the main thread.
おそらく一番エキサイティングな部分は「async rendering」でしょう。
This demo provides an early peek at the types of problems async rendering can solve:
Tip: Pay attention to the spinning black square.
We think async rendering is a big deal, and represents the future of React. To make migration to v16.0 as smooth as possible, we’re not enabling any async features yet, but we’re excited to start rolling them out in the coming months. Stay tuned!
Installation
React v16.0.0 is available on the npm registry.
React v16.0.0 は npm レジストリ上で手に入れることができます。
To install React 16 with Yarn, run:
Yarn を用いて React 16 をインストールするには、次のコマンドを実行してください。
yarn add react@^16.0.0 react-dom@^16.0.0
To install React 16 with npm, run:
npm を用いて React 16 をインストールするには、次のコマンドを実行してください。
npm install --save react@^16.0.0 react-dom@^16.0.0
We also provide UMD builds of React via a CDN:
また、React の UMD ビルドを 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>
Refer to the documentation for detailed installation instructions.
Upgrading
Although React 16 includes significant internal changes, in terms of upgrading, you can think of this like any other major React release. We’ve been serving React 16 to Facebook and Messenger.com users since earlier this year, and we released several beta and release candidate versions to flush out additional issues. With minor exceptions, if your app runs in 15.6 without any warnings, it should work in 16.
React 16 は莫大な内部変更が加えられましたが、アップグレードという観点からいえば、他の React メジャーバージョンアップのリリースと変わりません。我々は既に今年の初めには React 16 を Facebook や Messenger.com のサービスに使用しており、幾つかのベータ版と候補バージョンを出して、機能を追加してきました。いくつかの細かな例外を除けば、あなたのアプリケーションが 15.6 上で warning なしに動いているのであれば、基本的に 16 上でも動作します。
New deprecations
Hydrating a server-rendered container now has an explicit API. If you’re reviving server-rendered HTML, use ReactDOM.hydrate
instead of ReactDOM.render
. Keep using ReactDOM.render
if you’re just doing client-side rendering.
「Hydrating a server-rendered container」に関しては、新たに明示的な API を持つことになりました。「reviving server-rendered HTML」しているのであれば、ReactDOM.render ではなく ReactDOM.hydrate
を使用してください。単にクライアントサイドレンダリングをしている場合には、いつもどおりReactDOM.render を使用してください。
React Addons
As previously announced, we’ve discontinued support for React Addons. We expect the latest version of each addon (except react-addons-perf
; see below) to work for the foreseeable future, but we won’t publish additional updates.
既に発表した通り、React Addons のサポートを打ち切りました。それぞれのaddon の最終バージョンは、しばらく問題なく動くはずですが、しかし新たな更新をする予定はありません。
Refer to the previous announcement for suggestions on how to migrate.
react-addons-perf
no longer works at all in React 16. It’s likely that we’ll release a new version of this tool in the future. In the meantime, you can use your browser’s performance tools to profile React components.
react-addons-perf
は React 16 では動きません。おそらく新しいこういったツールを将来発表するはずです。しばらくのあいだは、ブラウザのパフォーマンスツールを使ってReact コンポーネントの捜査を行ってください。 (use your browser’s performance tools to profile React components.)
Breaking changes
破壊的変更
React 16 includes a number of small breaking changes. These only affect uncommon use cases and we don’t expect them to break most apps.
React 16 はかなりの数の破壊的変更が加えられました。これらが影響をあたえるのはかなり特殊なケースで運用されているアプリケーションに限られており、ほとんどのアプリケーションにおいて、動かなくなることはないと予想しています。
- React 15 had limited, undocumented support for error boundaries using
unstable_handleError
. This method has been renamed to componentDidCatch
. You can use a codemod to automatically migrate to the new API.
ReactDOM.render
and ReactDOM.unstable_renderIntoContainer
now return null if called from inside a lifecycle method. To work around this, you can use portals or refs.
setState
:
- Calling
setState
with null no longer triggers an update. This allows you to decide in an updater function if you want to re-render.
- Calling
setState
directly in render always causes an update. This was not previously the case. Regardless, you should not be calling setState from render.
setState
callbacks (second argument) now fire immediately after componentDidMount
/ componentDidUpdate
instead of after all components have rendered.
- When replacing
<A />
with <B />
, B.componentWillMount
now always happens beforeA.componentWillUnmount
. Previously, A.componentWillUnmount
could fire first in some cases.
- Previously, changing the ref to a component would always detach the ref before that component’s render is called. Now, we change the ref later, when applying the changes to the DOM.
- It is not safe to re-render into a container that was modified by something other than React. This worked previously in some cases but was never supported. We now emit a warning in this case. Instead you should clean up your component trees using
ReactDOM.unmountComponentAtNode
. See this example.
componentDidUpdate
lifecycle no longer receives prevContext
param. (See #8631)
- Shallow renderer no longer calls
componentDidUpdate
because DOM refs are not available. This also makes it consistent with componentDidMount
(which does not get called in previous versions either).
- Shallow renderer does not implement
unstable_batchedUpdates
anymore.
ReactDOM.unstable_batchedUpdates
now only takes one extra argument after the callback.
Packaging
- There is no
react/lib/*
and react-dom/lib/*
anymore. Even in CommonJS environments, React and ReactDOM are precompiled to single files (“flat bundles”). If you previously relied on undocumented React internals, and they don’t work anymore, let us know about your specific case in a new issue, and we’ll try to figure out a migration strategy for you.
- There is no
react-with-addons.js
build anymore. All compatible addons are published separately on npm, and have single-file browser versions if you need them.
- The deprecations introduced in 15.x have been removed from the core package.
React.createClass
is now available as create-react-class
, React.PropTypes
as prop-types
, React.DOM
as react-dom-factories
, react-addons-test-utils
as react-dom/test-utils
, and shallow renderer as react-test-renderer/shallow
. See 15.5.0 and 15.6.0 blog posts for instructions on migrating code and automated codemods.
- The names and paths to the single-file browser builds have changed to emphasize the difference between development and production builds. For example:
react/dist/react.js
→ react/umd/react.development.js
react/dist/react.min.js
→ react/umd/react.production.min.js
react-dom/dist/react-dom.js
→ react-dom/umd/react-dom.development.js
react-dom/dist/react-dom.min
.js → react-dom/umd/react-dom.production.min.js
JavaScript Environment Requirements
React 16 depends on the collection types Map and Set. If you support older browsers and devices which may not yet provide these natively (e.g. IE < 11), consider including a global polyfill in your bundled application, such as core-js or babel-polyfill.
React 16 は Map や Set に依存しています。そのためこれらをサポートしてない古いブラウザにおいては(例えばIE11未満)、グローバルな polyfill をバンドルアプリケーションに含めることを検討してください。例えば core-js や babel-polyfill などを用いてください。
A polyfilled environment for React 16 using core-js to support older browsers might look like:
次のソースは、古いブラウザでも react 16 が動くようにするために、core-js を用いて React 16 のための polyfill が適用された環境の例です。
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')
);
React also depends on requestAnimationFrame
(even in test environments). A simple shim for test environments would be:
React は requestAnimationFrame
にも依存しています。(テスト環境においても依存してます) テスト環境用のシンプルな shim は以下のようになります。
global.requestAnimationFrame = function(callback) {
setTimeout(callback, 0);
};
Acknowledgments
As always, this release would not have been possible without our open source contributors. Thanks to everyone who filed bugs, opened PRs, responded to issues, wrote documentation, and more!
Special thanks to our core contributors, especially for their heroic efforts over the past few weeks during the prerelease cycle: Brandon Dail, Jason Quense, Nathan Hunzaker, and Sasha Aickin.