Skip to content
91 changes: 46 additions & 45 deletions content/docs/state-and-lifecycle.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
---
id: state-and-lifecycle
title: State and Lifecycle
title: Стан та життєвий цикл
permalink: docs/state-and-lifecycle.html
redirect_from:
- "docs/interactivity-and-dynamic-uis.html"
prev: components-and-props.html
next: handling-events.html
---

This page introduces the concept of state and lifecycle in a React component. You can find a [detailed component API reference here](/docs/react-component.html).
На цій сторінці представлено поняття стану та життєвого циклу у React-компоненті. Ви можете знайти [детальньний API довідник на компонент тут](/docs/react-component.html).

Consider the ticking clock example from [one of the previous sections](/docs/rendering-elements.html#updating-the-rendered-element). In [Rendering Elements](/docs/rendering-elements.html#rendering-an-element-into-the-dom), we have only learned one way to update the UI. We call `ReactDOM.render()` to change the rendered output:
Розглянемо приклад відліку годинника з [одного з попередніх розділів] (/ docs / rendering-elements.html # updating-the-rendered-element).
В [Рендеринг елементів] (/ docs / rendering-elements.html # rendering-an-element-into-the-dom) ми дізналися лише один спосіб оновлення UI. Ми називаємо `ReactDOM.render ()`, щоб змінити відрендерний вивід інформації:

```js{8-11}
function tick() {
Expand All @@ -31,9 +32,9 @@ setInterval(tick, 1000);

[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwoJZk?editors=0010)

In this section, we will learn how to make the `Clock` component truly reusable and encapsulated. It will set up its own timer and update itself every second.
У цьому розділі ми дізнаємося, як зробити компонент 'Clock' дійсно багаторазовим та інкапсульованим. Компонент сам налаштує свій таймер та оновлюватиметься кожну секунду.

We can start by encapsulating how the clock looks:
Ми можемо почати з того, як виглядає годинник:

```js{3-6,12}
function Clock(props) {
Expand All @@ -55,11 +56,11 @@ function tick() {
setInterval(tick, 1000);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/dpdoYR?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/dpdoYR?editors=0010)

However, it misses a crucial requirement: the fact that the `Clock` sets up a timer and updates the UI every second should be an implementation detail of the `Clock`.
Однак, це пропускає важливу вимогу: той факт, що "Clock" встановлює таймер і оновлює UI кожну секунду, має бути деталлю реалізації "Clock".

Ideally we want to write this once and have the `Clock` update itself:
В ідеалі ми хочемо написати це один раз аби `Clock` оновлював себе сам:

```js{2}
ReactDOM.render(
Expand All @@ -68,25 +69,26 @@ ReactDOM.render(
);
```

To implement this, we need to add "state" to the `Clock` component.
Аби це реалізувати, нам потрібно додати "state" до компонента 'Clock'.

State is similar to props, but it is private and fully controlled by the component.
Стан - подібний до пропсів, але він приватний і повністю контролюється компонентом.

We [mentioned before](/docs/components-and-props.html#functional-and-class-components) that components defined as classes have some additional features. Local state is exactly that: a feature available only to classes.
Ми [згадували раніше](/docs/components-and-props.html#functional-and-class-components), що компоненти, визначені як класи, мають деякі додаткові функції. Внутрішній стан - це і є функція яка доступна тільки для класів.

## Converting a Function to a Class {#converting-a-function-to-a-class}
## Перетворення функції на клас {#converting-a-function-to-a-class}

You can convert a function component like `Clock` to a class in five steps:
Ви можете перетворити функцію компоненту `Clock` на клас у п'ять кроків:

1. Create an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), with the same name, that extends `React.Component`.
1. Створіть клас [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) з тим же ім'ям, що продовжує `React.Component`.

2. Add a single empty method to it called `render()`.
2. Додайте до нього один порожній метод, який називається `render()`.

3. Move the body of the function into the `render()` method.
3. Перемістіть зміст функції в метод `render()`.

4. Replace `props` with `this.props` in the `render()` body.
4. Замініть `props` на` this.props` в змісті `render()`.

5. Delete the remaining empty function declaration.
Видаліть порожні оголошення функції які залишилися.
5. Видаліть порожні оголошення функції які залишилися.

```js
class Clock extends React.Component {
Expand All @@ -101,17 +103,17 @@ class Clock extends React.Component {
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010)

`Clock` is now defined as a class rather than a function.
`Clock` тепер визначається як клас, а не як функція.

The `render` method will be called each time an update happens, but as long as we render `<Clock />` into the same DOM node, only a single instance of the `Clock` class will be used. This lets us use additional features such as local state and lifecycle methods.
Метод `render` буде викликатися кожного разу, коли відбуватиметься оновлення, але до тих пір, поки ми рендеремо `<Clock />` в той же вузол DOM, буде використано лише один екземпляр класу `Clock`. Це дозволяє нам використовувати додаткові функції, такі як методи внутрішнього стану та життєвого циклу.

## Додавання внутрішнього стану до класу {#adding-local-state-to-a-class}

## Adding Local State to a Class {#adding-local-state-to-a-class}
Ми перемістимо `date` від пропсів до стану, в три етапи:

We will move the `date` from props to state in three steps:

1) Replace `this.props.date` with `this.state.date` in the `render()` method:
1) Замінити `this.props.date` на `this.state.date` у методі `render()`:

```js{6}
class Clock extends React.Component {
Expand All @@ -126,7 +128,7 @@ class Clock extends React.Component {
}
```

2) Add a [class constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor) that assigns the initial `this.state`:
2) Додайте [class constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor), який призначає початковий `this.state`:

```js{4}
class Clock extends React.Component {
Expand All @@ -146,29 +148,28 @@ class Clock extends React.Component {
}
```

Note how we pass `props` to the base constructor:
Зверніть увагу на те, як ми передаємо `props`(пропси) базовому конструктору:


```js{2}
constructor(props) {
super(props);
this.state = {date: new Date()};
}
```
Компоненти класу повинні завжди викликати базовий конструктор з `props`.

Class components should always call the base constructor with `props`.

3) Remove the `date` prop from the `<Clock />` element:
3) Видалити елемент `date` з елемента `<Clock />`:

```js{2}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
```
Пізніше ми додамо код таймера назад до самого компонента.

We will later add the timer code back to the component itself.

The result looks like this:
Результат виглядає так:

```js{2-5,11,18}
class Clock extends React.Component {
Expand All @@ -193,19 +194,19 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010)

Next, we'll make the `Clock` set up its own timer and update itself every second.
Далі, ми зробимо так аби `Clock` сам налаштувати свій таймер і оновлювався себе кожну секунду.

## Adding Lifecycle Methods to a Class {#adding-lifecycle-methods-to-a-class}
## Додавання методів життєвого циклу до класу {#adding-lifecycle-methods-to-a-class}

In applications with many components, it's very important to free up resources taken by the components when they are destroyed.
У додатках з багатьма компонентами дуже важливо вивільнити ресурси, що вилучаються компонентами, коли вони знищуються.

We want to [set up a timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) whenever the `Clock` is rendered to the DOM for the first time. This is called "mounting" in React.
Ми хочемо [налаштувати таймер](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) всякий раз, коли `Clock` буде передано DOM вперше. Це називається "монтаж" в React.

We also want to [clear that timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) whenever the DOM produced by the `Clock` is removed. This is called "unmounting" in React.
Ми також хочемо [оновити цей таймер](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval), коли DOM видаляється. Це називається "розмотування" в React.

We can declare special methods on the component class to run some code when a component mounts and unmounts:
Ми можемо оголосити спеціальні методи на класі компонентів для запуску деякого коду, коли компонент монтується і розмотується:

```js{7-9,11-13}
class Clock extends React.Component {
Expand Down Expand Up @@ -233,9 +234,9 @@ class Clock extends React.Component {
}
```

These methods are called "lifecycle methods".
Ці методи називаються "методами життєвого циклу".

The `componentDidMount()` method runs after the component output has been rendered to the DOM. This is a good place to set up a timer:
Метод `componentDidMount()` виконується після того, як компонентний вивід був переданий DOM. Це гарне місце для налаштування таймера:

```js{2-5}
componentDidMount() {
Expand Down Expand Up @@ -302,7 +303,7 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010)

Now the clock ticks every second.

Expand Down Expand Up @@ -437,7 +438,7 @@ function FormattedDate(props) {
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRqNB?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/zKRqNB?editors=0010)

This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree.

Expand All @@ -462,7 +463,7 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010)

Each `Clock` sets up its own timer and updates independently.

Expand Down