` - any of those will lead to a full rebuild.
+При демонтуванні дерева старі DOM-вузли видаляються. Для екземплярів компонента настає метод життєвого циклу `componentWillUnmount()`. При створенні нового дерева нові DOM-вузли вставляють в DOM. Для екземплярів компонента настає метод життєвого циклу `componentWillMount()`, після нього — `componentDidMount()`. Будь-який стан, пов'язаний зі старим деревом, втрачається.
-When tearing down a tree, old DOM nodes are destroyed. Component instances receive `componentWillUnmount()`. When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive `componentWillMount()` and then `componentDidMount()`. Any state associated with the old tree is lost.
-
-Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:
+Будь-які компоненти, розташовані всередині кореневого, демонтуються, а їх стан втрачається. Наприклад, при порівнянні:
```xml
@@ -41,11 +40,11 @@ Any components below the root will also get unmounted and have their state destr
```
-This will destroy the old `Counter` and remount a new one.
+React демонтує старий `Counter` і змонтує новий.
-### DOM Elements Of The Same Type {#dom-elements-of-the-same-type}
+### DOM-елементи одного типу {#dom-elements-of-the-same-type}
-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:
+При порівнянні двох React DOM-елментів одного типу React розглядає атрибути обох, зберігає DOM-вузол, що лежить в їх основі, і оновлює тільки змінені атрибути. Наприклад:
```xml
@@ -53,9 +52,9 @@ When comparing two React DOM elements of the same type, React looks at the attri
```
-By comparing these two elements, React knows to only modify the `className` on the underlying DOM node.
+Порівнюючи два таких елементи, React знає, що потрібно змінити тільки `className` в базового DOM-елемента.
-When updating `style`, React also knows to update only the properties that changed. For example:
+При оновленні атрибута `style`, React також знає, що потрібно оновлювати тільки одну властивість, яка була змінена. Наприклад:
```xml
@@ -63,21 +62,21 @@ When updating `style`, React also knows to update only the properties that chang
```
-When converting between these two elements, React knows to only modify the `color` style, not the `fontWeight`.
+При такому перетворенні React знає, що потрібно змінити тільки значення властивості `color`, а `fontWeight` — залишити без змін.
-After handling the DOM node, React then recurses on the children.
+Після оновлення DOM-вузла React рекурсивно виконає такі самії дії з дочірніми елементами.
-### Component Elements Of The Same Type {#component-elements-of-the-same-type}
+### Елементи компонентів одного типу {#component-elements-of-the-same-type}
-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 `componentWillReceiveProps()` and `componentWillUpdate()` on the underlying instance.
+Коли компонент оновлюється, його екземпляр залишається без змін, саме тому стан зберігається між рендерами. React оновлює пропси базового екземпляра компонента, щоб він відповідав новому елементу, і викликає методи життєвого циклу `componentWillReceiveProps()` і `componentWillUpdate()` на базовому екзумплярі.
-Next, the `render()` method is called and the diff algorithm recurses on the previous result and the new result.
+Після цього викликається метод `render()`, і алгоритм порівняння рекурсивно обходить попередній і новий результати.
-### Recursing On Children {#recursing-on-children}
+### Рекурсія по дочірнім елементам {#recursing-on-children}
-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's a difference.
+За замовчуванням під час рекурсивного обходу дочірніх елементів DOM-вузла React просто виконує обхід обох списків потомків і формує зміни кожний раз, коли знаходить відмінності.
-For example, when adding an element at the end of the children, converting between these two trees works well:
+Наприклад, при додаванні нового елемента в кінець списку потомків, перетворення між цими двома деревами виконується добре:
```xml
@@ -92,9 +91,9 @@ For example, when adding an element at the end of the children, converting betwe
```
-React will match the two `
first` trees, match the two `
second` trees, and then insert the `
third` tree.
+React порівняє два дерева `
first`, потім `
second`, після чого вставить дерево `
third`.
-If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly:
+Якщо ж спробувати вставити новий елемент на початок списку потомків, від цього зменшиться продуктивність. Наприклад, перетворення між цими двома деревами виконується неефективно:
```xml
@@ -109,11 +108,11 @@ If you implement it naively, inserting an element at the beginning has worse per
```
-React will mutate every child instead of realizing it can keep the `
Duke` and `
Villanova` subtrees intact. This inefficiency can be a problem.
+React буде змінювати кожний дочірній елемент замість того, щоб залишити піддерева `
Duke` і `
Villanova` без змін. Подібна неефективність може стати проблемою.
-### Keys {#keys}
+### Ключі {#keys}
-In order to solve this issue, React supports a `key` 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 `key` to our inefficient example above can make the tree conversion efficient:
+Для вирішення такої проблеми React використовує атрибут `key`. Коли дочірні елементи мають ключі, React використовує їх для того, щоб встановити відповідність дочірніх елементів у початковому дереві з аналогічними елементами наступного. Наприклад, якщо додати `key`для попереднього неефективного прикладу, то перетворення дерева елементів стане ефективним:
```xml
@@ -128,30 +127,30 @@ In order to solve this issue, React supports a `key` attribute. When children ha
```
-Now React knows that the element with key `'2014'` is the new one, and the elements with the keys `'2015'` and `'2016'` have just moved.
+Тепер React буде знати, що елемент з ключем `'2014'` — новий, а елементи з ключами `'2015'` і `'2016'` тільки що були переміщені.
-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:
+На практиці знайти ключ частіше за все не складно. Елемент, який ви хочете відобразити, вже може мати унікальний ID, тому ключ може бути отриманий прямо з ваших даних:
```js
{item.name}
```
-When that'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.
+Якщо ж унікального значення немає, ви можете додати нову властивсть ID до своєї моделі, або ж створити хеш частини вмісту для генерації ключа. При цьому ключа повинен бути унікальним серед всіх сусідніх елементів, а не унікальним глобально.
-As a last resort, you can pass an item's index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.
+На крайній випадок ви можете передати порядковий номер елементам масиву як ключ. Це буде працювати за умови, коли елементи ніколи не будуть змінювати свій порядок, їх перестановка виконуватиметься повільно.
-Reorders can also cause issues with component state when indexes are used as keys. Component instances are updated and reused based on their key. If the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways.
+При використанні індексів елементів як їх ключів перестановки можуть приводити до проблем зі станом компоненту. Екземпляри компонентів оновлюються і повторно використовуються на основі їх ключів. Якщо ключем є індекс, переміщення елемента змінить його. В результаті стан компонента, який рендерить, наприклад, неконтрольоване поле, може зміщуватись і оновлюватись неочікуваним способом.
-Here is [an example of the issues that can be caused by using indexes as keys](codepen://reconciliation/index-used-as-key) on CodePen, and here is [an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues](codepen://reconciliation/no-index-used-as-key).
+Тут на CodePen є приклади проблем, які можуть виникати при використанні індексів як ключів ([an example of the issues that can be caused by using indexes as keys](codepen://reconciliation/index-used-as-key)), а також оновлена версія того ж прикладу, де показані способи вирішення проблем з перестановкою, сортуванням і вставленням елементів на початок, якщо не використовувати індекси як ключі ([an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues](codepen://reconciliation/no-index-used-as-key)).
-## Tradeoffs {#tradeoffs}
+## Компроміси {#tradeoffs}
-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. Just to be clear, rerender in this context means calling `render` for all components, it doesn't mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.
+Важливо пам'ятати, що алгоритм узгодження є деталлю реалізації. React може повторно рендерити весь додаток у відповідь на кожну дію, кінцевий результат буде однаковим. Щоб було більш зрозуміло, повторний рендеринг в цьому контексті означає виклик функції `render` для всіх компонентів, але це не означає те, що React демонтує та змонтує їх заново. Він буде застосовувати відмінності у відповідності до правил, які були описані в попередніх розділах.
-We are regularly refining the heuristics in order to make common use cases faster. 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.
+Ми регулярно здійснюємо евристику, щоб прискорити варіанти використання, які зустрічаються часто. В поточній реалізації ви можете припустити той факт, що піддерево перемістилось серед сусідніх елементів, але ви не можете стверджувати, що воно перемістилось в інше місце. Алгоритм буде повторно здійснювати рендеринг всього піддерева.
-Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.
+Оскільки React покладається на евристику, якщо припущення, на яких вона базується, не будуть дотримані, знизиться продуктивність.
-1. 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't found this to be an issue.
+1. Алгоритм не буде намагатися порівнювати піддерева компонентів різних типів. Якщо ви помітите, що використовуєте два типи компонентів з виведенням однакових даних, буде краще, якщо зробити їх компонентами однакового типу. На практиці ми не виявили з цим ніяких проблем.
-2. Keys should be stable, predictable, and unique. Unstable keys (like those produced by `Math.random()`) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
+2. Ключі повинні бути незмінними, передбачуваними та унікальними. Ключі, що можуть змінюватись (наприклад, створені за допомогою `Math.random()`), будуть приводити до необов'язкового повторного створення багатьох екземплярів компонентів у DOM-вузлів, що може привести до зниження продуктивності і втрати стану дочірніх компонентів.