Files
react/docs/reconciliation.html
T
Dan Abramov 7bc32d9148 Rebuild
2017-06-26 18:29:28 +01:00

519 lines
23 KiB
HTML

<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Reconciliation - React</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:title" content="Reconciliation - React">
<meta property="og:type" content="website">
<meta property="og:url" content="https://facebook.github.io/react/docs/reconciliation.html">
<meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
<meta property="og:description" content="A JavaScript library for building user interfaces">
<meta property="fb:app_id" content="623268441017527">
<link rel="shortcut icon" href="/react/favicon.ico">
<link rel="alternate" type="application/rss+xml" title="React" href="https://facebook.github.io/react/feed.xml">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
<link rel="stylesheet" href="/react/css/syntax.css">
<link rel="stylesheet" href="/react/css/codemirror.css">
<link rel="stylesheet" href="/react/css/react.css">
<script src="//use.typekit.net/vqa1hcx.js"></script>
<script>try{Typekit.load();}catch(e){}</script>
<!--[if lte IE 8]>
<script src="https://unpkg.com/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://unpkg.com/es5-shim@4.5.9/es5-shim.min.js"></script>
<script src="https://unpkg.com/es5-shim@4.5.9/es5-sham.min.js"></script>
<![endif]-->
<script src="https://unpkg.com/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
<script src="https://unpkg.com/codemirror@5.15.2"></script>
<script src="https://unpkg.com/codemirror@5.15.2/mode/javascript/javascript.js"></script>
<script src="https://unpkg.com/codemirror@5.15.2/mode/xml/xml.js"></script>
<script src="https://unpkg.com/codemirror@5.15.2/mode/jsx/jsx.js"></script>
<script src="https://unpkg.com/react/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script src="/react/js/live_editor.js"></script>
</head>
<body>
<div class="container">
<div class="nav-main">
<div class="wrap">
<a class="nav-home" href="/react/">
<img class="nav-logo" src="/react/img/logo.svg" width="36" height="36">
React
</a>
<div class="nav-lists">
<ul class="nav-site nav-site-internal">
<li><a href="/react/docs/hello-world.html" class="active">Docs</a></li>
<li><a href="/react/tutorial/tutorial.html">Tutorial</a></li>
<li><a href="/react/community/support.html">Community</a></li>
<li><a href="/react/blog/">Blog</a></li>
<li class="nav-site-search">
<input id="algolia-doc-search" type="text" placeholder="Search docs..." />
</li>
</ul>
<ul class="nav-site nav-site-external">
<li><a href="https://github.com/facebook/react">GitHub</a></li>
<li><a href="https://github.com/facebook/react/releases">v15.6.1</a></li>
</ul>
</div>
</div>
</div>
<section class="content wrap documentationContent">
<div class="inner-content">
<a class="edit-page-link" href="https://github.com/facebook/react/tree/master/docs/docs/reconciliation.md" target="_blank">Edit on GitHub</a>
<h1>
Reconciliation
</h1>
<div class="subHeader"></div>
<p>React provides a declarative API so that you don&#39;t have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React&#39;s &quot;diffing&quot; algorithm so that component updates are predictable while being fast enough for high-performance apps.</p>
<h2>Motivation</h2>
<p>When you use React, at a single point in time you can think of the <code>render()</code> function as creating a tree of React elements. On the next state or props update, that <code>render()</code> function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.</p>
<p>There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the <a href="http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf">state of the art algorithms</a> have a complexity in the order of O(n<sup>3</sup>) where n is the number of elements in the tree.</p>
<p>If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:</p>
<ol>
<li>Two elements of different types will produce different trees.</li>
<li>The developer can hint at which child elements may be stable across different renders with a <code>key</code> prop.</li>
</ol>
<p>In practice, these assumptions are valid for almost all practical use cases.</p>
<h2>The Diffing Algorithm</h2>
<p>When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.</p>
<h3>Elements Of Different Types</h3>
<p>Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from <code>&lt;a&gt;</code> to <code>&lt;img&gt;</code>, or from <code>&lt;Article&gt;</code> to <code>&lt;Comment&gt;</code>, or from <code>&lt;Button&gt;</code> to <code>&lt;div&gt;</code> - any of those will lead to a full rebuild.</p>
<p>When tearing down a tree, old DOM nodes are destroyed. Component instances receive <code>componentWillUnmount()</code>. When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive <code>componentWillMount()</code> and then <code>componentDidMount()</code>. Any state associated with the old tree is lost.</p>
<p>Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:</p>
<div class="highlight"><pre><code class="language-xml" data-lang="xml"><span class="nt">&lt;div&gt;</span>
<span class="nt">&lt;Counter</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;span&gt;</span>
<span class="nt">&lt;Counter</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/span&gt;</span>
</code></pre></div>
<p>This will destroy the old <code>Counter</code> and remount a new one.</p>
<h3>DOM Elements Of The Same Type</h3>
<p>When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For example:</p>
<div class="highlight"><pre><code class="language-xml" data-lang="xml"><span class="nt">&lt;div</span> <span class="na">className=</span><span class="s">&quot;before&quot;</span> <span class="na">title=</span><span class="s">&quot;stuff&quot;</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;div</span> <span class="na">className=</span><span class="s">&quot;after&quot;</span> <span class="na">title=</span><span class="s">&quot;stuff&quot;</span> <span class="nt">/&gt;</span>
</code></pre></div>
<p>By comparing these two elements, React knows to only modify the <code>className</code> on the underlying DOM node.</p>
<p>When updating <code>style</code>, React also knows to update only the properties that changed. For example:</p>
<div class="highlight"><pre><code class="language-xml" data-lang="xml"><span class="nt">&lt;div</span> <span class="na">style=</span><span class="s">{{color:</span> <span class="err">&#39;red&#39;,</span> <span class="err">fontWeight:</span> <span class="err">&#39;bold&#39;}}</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;div</span> <span class="na">style=</span><span class="s">{{color:</span> <span class="err">&#39;green&#39;,</span> <span class="err">fontWeight:</span> <span class="err">&#39;bold&#39;}}</span> <span class="nt">/&gt;</span>
</code></pre></div>
<p>When converting between these two elements, React knows to only modify the <code>color</code> style, not the <code>fontWeight</code>.</p>
<p>After handling the DOM node, React then recurses on the children.</p>
<h3>Component Elements Of The Same Type</h3>
<p>When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls <code>componentWillReceiveProps()</code> and <code>componentWillUpdate()</code> on the underlying instance.</p>
<p>Next, the <code>render()</code> method is called and the diff algorithm recurses on the previous result and the new result.</p>
<h3>Recursing On Children</h3>
<p>By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there&#39;s a difference.</p>
<p>For example, when adding an element at the end of the children, converting between these two trees works well:</p>
<div class="highlight"><pre><code class="language-xml" data-lang="xml"><span class="nt">&lt;ul&gt;</span>
<span class="nt">&lt;li&gt;</span>first<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li&gt;</span>second<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;ul&gt;</span>
<span class="nt">&lt;li&gt;</span>first<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li&gt;</span>second<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li&gt;</span>third<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
</code></pre></div>
<p>React will match the two <code>&lt;li&gt;first&lt;/li&gt;</code> trees, match the two <code>&lt;li&gt;second&lt;/li&gt;</code> trees, and then insert the <code>&lt;li&gt;third&lt;/li&gt;</code> tree.</p>
<p>If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly:</p>
<div class="highlight"><pre><code class="language-xml" data-lang="xml"><span class="nt">&lt;ul&gt;</span>
<span class="nt">&lt;li&gt;</span>Duke<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li&gt;</span>Villanova<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;ul&gt;</span>
<span class="nt">&lt;li&gt;</span>Connecticut<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li&gt;</span>Duke<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li&gt;</span>Villanova<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
</code></pre></div>
<p>React will mutate every child instead of realizing it can keep the <code>&lt;li&gt;Duke&lt;/li&gt;</code> and <code>&lt;li&gt;Villanova&lt;/li&gt;</code> subtrees intact. This inefficiency can be a problem.</p>
<h3>Keys</h3>
<p>In order to solve this issue, React supports a <code>key</code> attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a <code>key</code> to our inefficient example above can make the tree conversion efficient:</p>
<div class="highlight"><pre><code class="language-xml" data-lang="xml"><span class="nt">&lt;ul&gt;</span>
<span class="nt">&lt;li</span> <span class="na">key=</span><span class="s">&quot;2015&quot;</span><span class="nt">&gt;</span>Duke<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li</span> <span class="na">key=</span><span class="s">&quot;2016&quot;</span><span class="nt">&gt;</span>Villanova<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;ul&gt;</span>
<span class="nt">&lt;li</span> <span class="na">key=</span><span class="s">&quot;2014&quot;</span><span class="nt">&gt;</span>Connecticut<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li</span> <span class="na">key=</span><span class="s">&quot;2015&quot;</span><span class="nt">&gt;</span>Duke<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;li</span> <span class="na">key=</span><span class="s">&quot;2016&quot;</span><span class="nt">&gt;</span>Villanova<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
</code></pre></div>
<p>Now React knows that the element with key <code>&#39;2014&#39;</code> is the new one, and the elements with the keys <code>&#39;2015&#39;</code> and <code>&#39;2016&#39;</code> have just moved.</p>
<p>In practice, finding a key is usually not hard. The element you are going to display may already have a unique ID, so the key can just come from your data:</p>
<div class="highlight"><pre><code class="language-js" data-lang="js"><span class="o">&lt;</span><span class="nx">li</span> <span class="nx">key</span><span class="o">=</span><span class="p">{</span><span class="nx">item</span><span class="p">.</span><span class="nx">id</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">item</span><span class="p">.</span><span class="nx">name</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/li&gt;</span>
</code></pre></div>
<p>When that&#39;s not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. The key only has to be unique among its siblings, not globally unique.</p>
<p>As a last resort, you can pass item&#39;s index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.</p>
<h2>Tradeoffs</h2>
<p>It is important to remember that the reconciliation algorithm is an implementation detail. React could rerender the whole app on every action; the end result would be the same. We are regularly refining the heuristics in order to make common use cases faster.</p>
<p>In the current implementation, you can express the fact that a subtree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will rerender that full subtree.</p>
<p>Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.</p>
<ol>
<li><p>The algorithm will not try to match subtrees of different component types. If you see yourself alternating between two component types with very similar output, you may want to make it the same type. In practice, we haven&#39;t found this to be an issue.</p></li>
<li><p>Keys should be stable, predictable, and unique. Unstable keys (like those produced by <code>Math.random()</code>) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.</p></li>
</ol>
<div class="docs-prevnext">
</div>
</div>
<div class="nav-docs">
<!-- Docs Nav -->
<div class="nav-docs-section">
<h3>Quick Start</h3>
<ul>
<li>
<a href="/react/docs/installation.html">Installation</a>
</li>
<li>
<a href="/react/docs/hello-world.html">Hello World</a>
</li>
<li>
<a href="/react/docs/introducing-jsx.html">Introducing JSX</a>
</li>
<li>
<a href="/react/docs/rendering-elements.html">Rendering Elements</a>
</li>
<li>
<a href="/react/docs/components-and-props.html">Components and Props</a>
</li>
<li>
<a href="/react/docs/state-and-lifecycle.html">State and Lifecycle</a>
</li>
<li>
<a href="/react/docs/handling-events.html">Handling Events</a>
</li>
<li>
<a href="/react/docs/conditional-rendering.html">Conditional Rendering</a>
</li>
<li>
<a href="/react/docs/lists-and-keys.html">Lists and Keys</a>
</li>
<li>
<a href="/react/docs/forms.html">Forms</a>
</li>
<li>
<a href="/react/docs/lifting-state-up.html">Lifting State Up</a>
</li>
<li>
<a href="/react/docs/composition-vs-inheritance.html">Composition vs Inheritance</a>
</li>
<li>
<a href="/react/docs/thinking-in-react.html">Thinking In React</a>
</li>
</ul>
</div>
<div class="nav-docs-section">
<h3>Advanced Guides</h3>
<ul>
<li>
<a href="/react/docs/jsx-in-depth.html">JSX In Depth</a>
</li>
<li>
<a href="/react/docs/typechecking-with-proptypes.html">Typechecking With PropTypes</a>
</li>
<li>
<a href="/react/docs/refs-and-the-dom.html">Refs and the DOM</a>
</li>
<li>
<a href="/react/docs/uncontrolled-components.html">Uncontrolled Components</a>
</li>
<li>
<a href="/react/docs/optimizing-performance.html">Optimizing Performance</a>
</li>
<li>
<a href="/react/docs/react-without-es6.html">React Without ES6</a>
</li>
<li>
<a href="/react/docs/react-without-jsx.html">React Without JSX</a>
</li>
<li>
<a href="/react/docs/reconciliation.html" class="active">Reconciliation</a>
</li>
<li>
<a href="/react/docs/context.html">Context</a>
</li>
<li>
<a href="/react/docs/web-components.html">Web Components</a>
</li>
<li>
<a href="/react/docs/higher-order-components.html">Higher-Order Components</a>
</li>
<li>
<a href="/react/docs/integrating-with-other-libraries.html">Integrating with Other Libraries</a>
</li>
<li>
<a href="/react/docs/accessibility.html">Accessibility</a>
</li>
</ul>
</div>
<div class="nav-docs-section">
<h3>Reference</h3>
<ul>
<li>
<a href="/react/docs/react-api.html">React</a>
<ul>
<li>
<a href="/react/docs/react-component.html">React.Component</a>
</li>
</ul>
</li>
<li>
<a href="/react/docs/react-dom.html">ReactDOM</a>
</li>
<li>
<a href="/react/docs/react-dom-server.html">ReactDOMServer</a>
</li>
<li>
<a href="/react/docs/dom-elements.html">DOM Elements</a>
</li>
<li>
<a href="/react/docs/events.html">SyntheticEvent</a>
</li>
<li>
<a href="/react/docs/test-utils.html">Test Utilities</a>
</li>
<li>
<a href="/react/docs/shallow-renderer.html">Shallow Renderer</a>
</li>
</ul>
</div>
<!-- Contributing Nav -->
<div class="nav-docs-section">
<h3>Contributing</h3>
<ul>
<li>
<a href="/react/contributing/how-to-contribute.html">How to Contribute</a>
</li>
<li>
<a href="/react/contributing/codebase-overview.html">Codebase Overview</a>
</li>
<li>
<a href="/react/contributing/implementation-notes.html">Implementation Notes</a>
</li>
<li>
<a href="/react/contributing/design-principles.html">Design Principles</a>
</li>
</ul>
</div>
</div>
</section>
<footer class="nav-footer">
<section class="sitemap">
<a href="/react/" class="nav-home">
</a>
<div>
<h5><a href="/react/docs/">Docs</a></h5>
<a href="/react/docs/hello-world.html">Quick Start</a>
<a href="/react/docs/thinking-in-react.html">Thinking in React</a>
<a href="/react/tutorial/tutorial.html">Tutorial</a>
<a href="/react/docs/jsx-in-depth.html">Advanced Guides</a>
</div>
<div>
<h5><a href="/react/community/support.html">Community</a></h5>
<a href="http://stackoverflow.com/questions/tagged/reactjs" target="_blank">Stack Overflow</a>
<a href="https://discuss.reactjs.org/" target="_blank">Discussion Forum</a>
<a href="https://discord.gg/0ZcbPKXt5bZjGY5n" target="_blank">Reactiflux Chat</a>
<a href="https://www.facebook.com/react" target="_blank">Facebook</a>
<a href="https://twitter.com/reactjs" target="_blank">Twitter</a>
</div>
<div>
<h5><a href="/react/community/support.html">Resources</a></h5>
<a href="/react/community/conferences.html">Conferences</a>
<a href="/react/community/videos.html">Videos</a>
<a href="https://github.com/facebook/react/wiki/Examples" target="_blank">Examples</a>
<a href="https://github.com/facebook/react/wiki/Complementary-Tools" target="_blank">Complementary Tools</a>
</div>
<div>
<h5>More</h5>
<a href="/react/blog/">Blog</a>
<a href="https://github.com/facebook/react" target="_blank">GitHub</a>
<a href="http://facebook.github.io/react-native/" target="_blank">React Native</a>
<a href="/react/acknowledgements.html">Acknowledgements</a>
</div>
</section>
<a href="https://code.facebook.com/projects/" target="_blank" class="fbOpenSource">
<img src="/react/img/oss_logo.png" alt="Facebook Open Source" width="170" height="45"/>
</a>
<section class="copyright">
Copyright © 2017 Facebook Inc.
</section>
</footer>
</div>
<div id="fb-root"></div>
<script src="/react/js/anchor-links.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41298772-1', 'facebook.github.io');
ga('send', 'pageview');
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6&appId=623268441017527";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
docsearch({
apiKey: '36221914cce388c46d0420343e0bb32e',
indexName: 'react',
inputSelector: '#algolia-doc-search'
});
</script>
</body>
</html>