`, який ми додали до нашого HTML-файлу в першому кроці і потім відображає React-компонент кнопки "Мені подобається" всередині нього.
@@ -94,7 +104,7 @@ ReactDOM.render(e(LikeButton), domContainer);
**[Подивитися фінальний код прикладу](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605)**
-**[Завантажити код прикладу (2Кб в архіві)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)**
+**[Завантажити код прикладу (2Кб в архіві)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/87f0b6f34238595b44308acfb86df6ea43669c08.zip)**
### Порада: Повторно використовуйте компоненти {#tip-reuse-a-component}
@@ -102,7 +112,7 @@ ReactDOM.render(e(LikeButton), domContainer);
[Подивитися повний першокод](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda)
-[Завантажити код прикладу (2Кб в архіві)](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda/archive/9d0dd0ee941fea05fd1357502e5aa348abb84c12.zip)
+[Завантажити код прикладу (2Кб в архіві)](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda/archive/279839cb9891bd41802ebebc5365e9dec08eeb9f.zip)
>Примітка
>
@@ -115,8 +125,8 @@ ReactDOM.render(e(LikeButton), domContainer);
Якщо ви вже стискаєте скрипти вашого додатку, **то ваш сайт буде готовим для публікації на продакшн**, якщо ви впевнитесь в тому, що опублікована HTML-сторінка завантажує версії React, які закінчуються на `production.min.js`:
```js
-
-
+
+
```
Якщо ви ще не налаштували стискання для ваших скриптів, то [цей варіант може вам допомогти із цим](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3).
@@ -149,7 +159,7 @@ return (
Ці два приклади виконують одну і ту ж річ. Незважаючи на те, що **JSX є [цілком необов'язковим](/docs/react-without-jsx.html)**, багато людей вважають його зручним для розробки інтерфейсів користувача -- як із React, так і з іншими бібліотеками.
-Ви можете спробувати JSX [у цьому онлайн-конвертері](https://babeljs.io/en/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=DwIwrgLhD2B2AEcDCAbAlgYwNYF4DeAFAJTw4B88EAFmgM4B0tAphAMoQCGETBe86WJgBMAXJQBOYJvAC-RGWQBQ8FfAAyaQYuAB6cFDhkgA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.3).
+Ви можете спробувати JSX [у цьому онлайн-конвертері](https://babeljs.io/en/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=DwIwrgLhD2B2AEcDCAbAlgYwNYF4DeAFAJTw4B88EAFmgM4B0tAphAMoQCGETBe86WJgBMAXJQBOYJvAC-RGWQBQ8FfAAyaQYuAB6cFDhkgA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.15.7).
### Швидкий старт з JSX {#quickly-try-jsx}
@@ -159,7 +169,7 @@ return (
```
-Тепер ви можете використовувати JSX в будь-якому `
-
+
+
```
Зазначені вище версії призначені тільки при розробці програми, але не підходять для використання в продакшн-оточенні. Мініфіковані та оптимізовані для продакшн версії React перераховані нижче:
```html
-
-
+
+
```
-Щоб завантажити конкретну версію `react` та `react-dom`, замініть `16` на номер версії, яка вам потрібна.
+Щоб завантажити конкретну версію `react` та `react-dom`, замініть `18` на номер версії, яка вам потрібна.
### Для чого атрибут `crossorigin`? {#why-the-crossorigin-attribute}
diff --git a/content/docs/code-splitting.md b/content/docs/code-splitting.md
index 37122fad9..9808e8082 100644
--- a/content/docs/code-splitting.md
+++ b/content/docs/code-splitting.md
@@ -4,12 +4,20 @@ title: Розбиття коду
permalink: docs/code-splitting.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [`lazy`](https://react.dev/reference/react/lazy)
+> - [``](https://react.dev/reference/react/Suspense)
+
+
+
## Зшивання файлів {#bundling}
-Файли більшості React-додатків зшиваються разом за допомогою таких інструментів, як
-[Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/) та
-[Browserify](http://browserify.org/).
-Зшивання (бандлінг) – це процес об'єднання імпортованих файлів в один файл – бандл.
+Файли більшості React-додатків зшиваються разом за допомогою таких інструментів, як [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/) та [Browserify](http://browserify.org/). Зшивання (бандлінг) – це процес об'єднання імпортованих файлів в один файл – бандл.
Цей бандл потім може бути включений до веб-сторінки для завантаження всього додатку
одночасно.
@@ -47,9 +55,7 @@ console.log(add(16, 26)); // 42
Якщо ви використовуєте [Create React App](https://create-react-app.dev/), [Next.js](https://nextjs.org/), [Gatsby](https://www.gatsbyjs.org/) чи подібний інструмент, Webpack за замовчуванням налаштований для бандлінгу вашого додатку.
-Якщо ви не використовуєте нічого з наведеного чи подібного, вам доведеться налаштувати бандлінг самостійно. Для прикладів ознайомтеся зі
-[Встановленням](https://webpack.js.org/guides/installation/) та
-[Початком роботи](https://webpack.js.org/guides/getting-started/) в офіційній
+Якщо ви не використовуєте нічого з наведеного чи подібного, вам доведеться налаштувати бандлінг самостійно. Для прикладів ознайомтеся зі [Встановленням](https://webpack.js.org/guides/installation/) та [Початком роботи](https://webpack.js.org/guides/getting-started/) в офіційній
документації Webpack.
## Розбиття Коду {#code-splitting}
@@ -93,20 +99,15 @@ import("./math").then(math => {
```
Коли Webpack стикається з таким синтаксисом, він автоматично починає розбивати код вашого додатку.
-Якщо ви користуєтесь Create React App, він вже налаштований відповідним чином, і ви можете одразу почати [користуватися розбиттям коду](https://facebook.github.io/create-react-app/docs/code-splitting). У [Next.js](https://nextjs.org/docs/advanced-features/dynamic-import) розбиття коду також підтримується за замовчуванням.
+Якщо ви користуєтесь Create React App, він вже налаштований відповідним чином, і ви можете одразу почати [користуватися розбиттям коду](https://create-react-app.dev/docs/code-splitting/). У [Next.js](https://nextjs.org/docs/advanced-features/dynamic-import) розбиття коду також підтримується за замовчуванням.
-Під час самостійного налаштування Webpack, скоріш за все, у вас з'явиться бажання прочитати
-[інструкцію з розбиття коду](https://webpack.js.org/guides/code-splitting/) від Webpack. Конфігурація вашого Webpack повинна мати вигляд, [схожий на цей](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).
+Під час самостійного налаштування Webpack, скоріш за все, у вас з'явиться бажання прочитати [інструкцію з розбиття коду](https://webpack.js.org/guides/code-splitting/) від Webpack. Конфігурація вашого Webpack повинна мати вигляд, [схожий на цей](https://gist.github.com/gaearon/ca6e803f5c604d37468b0091d9959269).
В разі використання [Babel](https://babeljs.io/) ви маєте пересвідчитись в тому, що Babel може парсити синтаксис динамічного import(), але не перетворює його.
-Для цього вам знадобиться [babel-plugin-syntax-dynamic-import](https://yarnpkg.com/en/package/babel-plugin-syntax-dynamic-import).
+Для цього вам знадобиться [@babel/plugin-syntax-dynamic-import](https://classic.yarnpkg.com/en/package/@babel/plugin-syntax-dynamic-import).
## `React.lazy` {#reactlazy}
-> Примітка:
->
-> `React.lazy` та Suspense ще не доступні для рендерингу на стороні сервера. Якщо ви хочете використовувати розбиття коду в додатках, відрендерених на сервері, ми рекомендуємо [Loadable Components](https://github.com/gregberge/loadable-components). Вони мають гарну [інструкцію для розбиття на бандли з використанням серверного рендерингу](https://loadable-components.com/docs/server-side-rendering/).
-
Функція `React.lazy` дозволяє вам рендерити динамічний import як звичайний компонент
**До:**
@@ -165,6 +166,52 @@ function MyComponent() {
}
```
+### Avoiding fallbacks {#avoiding-fallbacks}
+Any component may suspend as a result of rendering, even components that were already shown to the user. In order for screen content to always be consistent, if an already shown component suspends, React has to hide its tree up to the closest `` boundary. However, from the user's perspective, this can be disorienting.
+
+Consider this tab switcher:
+
+```js
+import React, { Suspense } from 'react';
+import Tabs from './Tabs';
+import Glimmer from './Glimmer';
+
+const Comments = React.lazy(() => import('./Comments'));
+const Photos = React.lazy(() => import('./Photos'));
+
+function MyComponent() {
+ const [tab, setTab] = React.useState('photos');
+
+ function handleTabSelect(tab) {
+ setTab(tab);
+ };
+
+ return (
+
+
+ }>
+ {tab === 'photos' ? : }
+
+
+ );
+}
+
+```
+
+In this example, if tab gets changed from `'photos'` to `'comments'`, but `Comments` suspends, the user will see a glimmer. This makes sense because the user no longer wants to see `Photos`, the `Comments` component is not ready to render anything, and React needs to keep the user experience consistent, so it has no choice but to show the `Glimmer` above.
+
+However, sometimes this user experience is not desirable. In particular, it is sometimes better to show the "old" UI while the new UI is being prepared. You can use the new [`startTransition`](/docs/react-api.html#starttransition) API to make React do this:
+
+```js
+function handleTabSelect(tab) {
+ startTransition(() => {
+ setTab(tab);
+ });
+}
+```
+
+Here, you tell React that setting tab to `'comments'` is not an urgent update, but is a [transition](/docs/react-api.html#transitions) that may take some time. React will then keep the old UI in place and interactive, and will switch to showing `` when it is ready. See [Transitions](/docs/react-api.html#transitions) for more info.
+
### Запобіжники {#error-boundaries}
Якщо інший модуль не зміг завантажитися (наприклад, через вимкнений інтернет), це призведе до помилки. Ви можете обробляти такі помилки, щоб створити гарний досвід користування і керувати відновленням за допомогою [Запобіжників](/docs/error-boundaries.html). Після створення запобіжника, його можна використовувати де завгодно над "ледачими" компонентами для того, щоб показати стан помилки, коли виникає проблема з мережею.
@@ -202,11 +249,11 @@ const MyComponent = () => (
з іншими елементами на сторінці в цей час.
Нижче наведено приклад налаштування розбиття коду на основі маршрутів, використовуючи
-бібліотеку [React Router](https://reacttraining.com/react-router/) за допомогою `React.lazy`.
+бібліотеку [React Router](https://reactrouter.com/) за допомогою `React.lazy`.
```js
import React, { Suspense, lazy } from 'react';
-import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
+import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
@@ -214,10 +261,10 @@ const About = lazy(() => import('./routes/About'));
const App = () => (
Завантаження...
}>
-
-
-
-
+
+ } />
+ } />
+
);
diff --git a/content/docs/codebase-overview.md b/content/docs/codebase-overview.md
index 2d4198040..5203c47e7 100644
--- a/content/docs/codebase-overview.md
+++ b/content/docs/codebase-overview.md
@@ -19,8 +19,8 @@ We don't necessarily recommend any of these conventions in React apps. Many of t
After cloning the [React repository](https://github.com/facebook/react), you will see a few top-level folders in it:
-* [`packages`](https://github.com/facebook/react/tree/master/packages) contains metadata (such as `package.json`) and the source code (`src` subdirectory) for all packages in the React repository. **If your change is related to the code, the `src` subdirectory of each package is where you'll spend most of your time.**
-* [`fixtures`](https://github.com/facebook/react/tree/master/fixtures) contains a few small React test applications for contributors.
+* [`packages`](https://github.com/facebook/react/tree/main/packages) contains metadata (such as `package.json`) and the source code (`src` subdirectory) for all packages in the React repository. **If your change is related to the code, the `src` subdirectory of each package is where you'll spend most of your time.**
+* [`fixtures`](https://github.com/facebook/react/tree/main/fixtures) contains a few small React test applications for contributors.
* `build` is the build output of React. It is not in the repository but it will appear in your React clone after you [build it](/docs/how-to-contribute.html#development-workflow) for the first time.
The documentation is hosted [in a separate repository from React](https://github.com/reactjs/reactjs.org).
@@ -98,7 +98,7 @@ React is a [monorepo](https://danluu.com/monorepo/). Its repository contains mul
### React Core {#react-core}
-The "core" of React includes all the [top-level `React` APIs](/docs/top-level-api.html#react), for example:
+The "core" of React includes all the [top-level `React` APIs](/docs/react-api.html#react), for example:
* `React.createElement()`
* `React.Component`
@@ -106,7 +106,7 @@ The "core" of React includes all the [top-level `React` APIs](/docs/top-level-ap
**React core only includes the APIs necessary to define components.** It does not include the [reconciliation](/docs/reconciliation.html) algorithm or any platform-specific code. It is used both by React DOM and React Native components.
-The code for React core is located in [`packages/react`](https://github.com/facebook/react/tree/master/packages/react) in the source tree. It is available on npm as the [`react`](https://www.npmjs.com/package/react) package. The corresponding standalone browser build is called `react.js`, and it exports a global called `React`.
+The code for React core is located in [`packages/react`](https://github.com/facebook/react/tree/main/packages/react) in the source tree. It is available on npm as the [`react`](https://www.npmjs.com/package/react) package. The corresponding standalone browser build is called `react.js`, and it exports a global called `React`.
### Renderers {#renderers}
@@ -114,17 +114,17 @@ React was originally created for the DOM but it was later adapted to also suppor
**Renderers manage how a React tree turns into the underlying platform calls.**
-Renderers are also located in [`packages/`](https://github.com/facebook/react/tree/master/packages/):
+Renderers are also located in [`packages/`](https://github.com/facebook/react/tree/main/packages/):
-* [React DOM Renderer](https://github.com/facebook/react/tree/master/packages/react-dom) renders React components to the DOM. It implements [top-level `ReactDOM` APIs](/docs/react-dom.html) and is available as [`react-dom`](https://www.npmjs.com/package/react-dom) npm package. It can also be used as standalone browser bundle called `react-dom.js` that exports a `ReactDOM` global.
-* [React Native Renderer](https://github.com/facebook/react/tree/master/packages/react-native-renderer) renders React components to native views. It is used internally by React Native.
-* [React Test Renderer](https://github.com/facebook/react/tree/master/packages/react-test-renderer) renders React components to JSON trees. It is used by the [Snapshot Testing](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) feature of [Jest](https://facebook.github.io/jest) and is available as [react-test-renderer](https://www.npmjs.com/package/react-test-renderer) npm package.
+* [React DOM Renderer](https://github.com/facebook/react/tree/main/packages/react-dom) renders React components to the DOM. It implements [top-level `ReactDOM` APIs](/docs/react-dom.html) and is available as [`react-dom`](https://www.npmjs.com/package/react-dom) npm package. It can also be used as standalone browser bundle called `react-dom.js` that exports a `ReactDOM` global.
+* [React Native Renderer](https://github.com/facebook/react/tree/main/packages/react-native-renderer) renders React components to native views. It is used internally by React Native.
+* [React Test Renderer](https://github.com/facebook/react/tree/main/packages/react-test-renderer) renders React components to JSON trees. It is used by the [Snapshot Testing](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) feature of [Jest](https://facebook.github.io/jest) and is available as [react-test-renderer](https://www.npmjs.com/package/react-test-renderer) npm package.
-The only other officially supported renderer is [`react-art`](https://github.com/facebook/react/tree/master/packages/react-art). It used to be in a separate [GitHub repository](https://github.com/reactjs/react-art) but we moved it into the main source tree for now.
+The only other officially supported renderer is [`react-art`](https://github.com/facebook/react/tree/main/packages/react-art). It used to be in a separate [GitHub repository](https://github.com/reactjs/react-art) but we moved it into the main source tree for now.
>**Note:**
>
->Technically the [`react-native-renderer`](https://github.com/facebook/react/tree/master/packages/react-native-renderer) is a very thin layer that teaches React to interact with React Native implementation. The real platform-specific code managing the native views lives in the [React Native repository](https://github.com/facebook/react-native) together with its components.
+>Technically the [`react-native-renderer`](https://github.com/facebook/react/tree/main/packages/react-native-renderer) is a very thin layer that teaches React to interact with React Native implementation. The real platform-specific code managing the native views lives in the [React Native repository](https://github.com/facebook/react-native) together with its components.
### Reconcilers {#reconcilers}
@@ -152,11 +152,11 @@ Its main goals are:
You can read more about React Fiber Architecture [here](https://github.com/acdlite/react-fiber-architecture) and [here](https://blog.ag-grid.com/inside-fiber-an-in-depth-overview-of-the-new-reconciliation-algorithm-in-react). While it has shipped with React 16, the async features are not enabled by default yet.
-Its source code is located in [`packages/react-reconciler`](https://github.com/facebook/react/tree/master/packages/react-reconciler).
+Its source code is located in [`packages/react-reconciler`](https://github.com/facebook/react/tree/main/packages/react-reconciler).
### Event System {#event-system}
-React implements a layer over native events to smooth out cross-browser differences. Its source code is located in [`packages/react-dom/src/events`](https://github.com/facebook/react/tree/master/packages/react-dom/src/events).
+React implements a layer over native events to smooth out cross-browser differences. Its source code is located in [`packages/react-dom/src/events`](https://github.com/facebook/react/tree/main/packages/react-dom/src/events).
### What Next? {#what-next}
diff --git a/content/docs/components-and-props.md b/content/docs/components-and-props.md
index 0b40fb29a..63ec7dec6 100644
--- a/content/docs/components-and-props.md
+++ b/content/docs/components-and-props.md
@@ -16,6 +16,18 @@ prev: rendering-elements.html
next: state-and-lifecycle.html
---
+
+
+>
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Your First Component](https://react.dev/learn/your-first-component)
+> - [Passing Props to a Component](https://react.dev/learn/passing-props-to-a-component)
+
+
+
Компоненти дозволяють розділити інтерфейс користувача на незалежні частини, придатні до повторного використання, і сприймати їх як такі, що функціонують окремо один від одного. На цій сторінці викладений вступ до ідеї компонентів. Ви можете знайти [докладний опис API компонентів тут](/docs/react-component.html).
Концептуально компоненти є подібними до функцій JavaScript. Вони приймають довільні вхідні дані (так звані "пропси") і повертають React-елементи, що описують те, що повинно з'явитися на екрані.
@@ -64,23 +76,21 @@ const element = ;
Наприклад, код нижче виводить на сторінці "Привіт, Василина":
-```js{1,5}
+```js{1,6}
function Welcome(props) {
return
Привіт, {props.name}
;
}
+const root = ReactDOM.createRoot(document.getElementById('root'));
const element = ;
-ReactDOM.render(
- element,
- document.getElementById('root')
-);
+root.render(element);
```
-[Спробуйте на CodePen](codepen://components-and-props/rendering-a-component)
+[Спробуйте на CodePen](https://codepen.io/gaearon/pen/YGYmEG?editors=1010)
Давайте розберемо, що відбувається в цьому прикладі:
-1. Ми викликаємо `ReactDOM.render()` з елементом ``.
+1. Ми викликаємо `root.render()` з елементом ``.
2. React викликає компонент `Welcome` з пропсом `{name: 'Василина'}`.
3. `Welcome` компонент повертає елемент `
Привіт, Василина
`.
4. React DOM ефективно оновлює DOM для отримання `
Привіт, Василина
`.
@@ -111,14 +121,9 @@ function App() {
);
}
-
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
```
-[Спробуйте на CodePen](codepen://components-and-props/composing-components)
+[Спробуйте на CodePen](https://codepen.io/gaearon/pen/KgQKPr?editors=1010)
Як правило, нові React-додатки мають єдиний компонент `App`, що знаходиться зверху дерева ієрархій елементів. Однак, якщо ви інтегруєте React у існуючий додаток, ви можете почати знизу вгору з невеликим компонентом, наприклад `Button`, і поступово працювати у верхній частині ієрархії перегляду.
@@ -152,7 +157,7 @@ function Comment(props) {
}
```
-[Спробуйте на CodePen](codepen://components-and-props/extracting-components)
+[Спробуйте на CodePen](https://codepen.io/gaearon/pen/VKQwEo?editors=1010)
Він приймає `author` (об'єкт), `text` (рядок) і `date` (дату) як пропси і представляє собою коментар в соціальній мережі.
@@ -231,7 +236,7 @@ function Comment(props) {
}
```
-[Спробуйте на CodePen](codepen://components-and-props/extracting-components-continued)
+[Спробуйте на CodePen](https://codepen.io/gaearon/pen/rrJNJY?editors=1010)
Розбиття компонентів може здатися спочатку невдячною роботою. Проте, у великих додатках така велика кількість багаторазових компонентів є дуже корисною. Суть в тому, що якщо частина вашого інтерфейсу використовується кілька разів (`Button`,`Panel`, `Avatar`), або сама собою досить складна (`App`, `FeedStory`,`Comment`), краще винести її в окремий компонент.
diff --git a/content/docs/composition-vs-inheritance.md b/content/docs/composition-vs-inheritance.md
index 8dc676523..9d25782b4 100644
--- a/content/docs/composition-vs-inheritance.md
+++ b/content/docs/composition-vs-inheritance.md
@@ -8,6 +8,12 @@ prev: lifting-state-up.html
next: thinking-in-react.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+
+
+
React має потужну модель композиції і ми рекомендуємо використовувати композицію замість наслідування для повторного використання коду між компонентами.
В цьому розділі ми розглянемо кілька проблем, котрі нові React-розробники вирішують за допомогою наслідування і покажемо, як вони вирішуються за допомогою композиції.
diff --git a/content/docs/concurrent-mode-adoption.md b/content/docs/concurrent-mode-adoption.md
deleted file mode 100644
index 720c34c17..000000000
--- a/content/docs/concurrent-mode-adoption.md
+++ /dev/null
@@ -1,141 +0,0 @@
----
-id: concurrent-mode-adoption
-title: Adopting Concurrent Mode (Experimental)
-permalink: docs/concurrent-mode-adoption.html
-prev: concurrent-mode-patterns.html
-next: concurrent-mode-reference.html
----
-
-
-
-
-
->Caution:
->
->This page describes **experimental features that are not yet available in a stable release**. Don't rely on experimental builds of React in production apps. These features may change significantly and without a warning before they become a part of React.
->
->This documentation is aimed at early adopters and people who are curious. **If you're new to React, don't worry about these features** -- you don't need to learn them right now.
-
-
-
-- [Installation](#installation)
- - [Who Is This Experimental Release For?](#who-is-this-experimental-release-for)
- - [Enabling Concurrent Mode](#enabling-concurrent-mode)
-- [What to Expect](#what-to-expect)
- - [Migration Step: Blocking Mode](#migration-step-blocking-mode)
- - [Why So Many Modes?](#why-so-many-modes)
- - [Feature Comparison](#feature-comparison)
-
-## Installation {#installation}
-
-Concurrent Mode is only available in the [experimental builds](/blog/2019/10/22/react-release-channels.html#experimental-channel) of React. To install them, run:
-
-```
-npm install react@experimental react-dom@experimental
-```
-
-**There are no semantic versioning guarantees for the experimental builds.**
-APIs may be added, changed, or removed with any `@experimental` release.
-
-**Experimental releases will have frequent breaking changes.**
-
-You can try these builds on personal projects or in a branch, but we don't recommend running them in production. At Facebook, we *do* run them in production, but that's because we're also there to fix bugs when something breaks. You've been warned!
-
-### Who Is This Experimental Release For? {#who-is-this-experimental-release-for}
-
-This release is primarily aimed at early adopters, library authors, and curious people.
-
-We're using this code in production (and it works for us) but there are still some bugs, missing features, and gaps in the documentation. We'd like to hear more about what breaks in Concurrent Mode so we can better prepare it for an official stable release in the future.
-
-### Enabling Concurrent Mode {#enabling-concurrent-mode}
-
-Normally, when we add features to React, you can start using them immediately. Fragments, Context, and even Hooks are examples of such features. You can use them in new code without making any changes to the existing code.
-
-Concurrent Mode is different. It introduces semantic changes to how React works. Otherwise, the [new features](/docs/concurrent-mode-patterns.html) enabled by it *wouldn't be possible*. This is why they're grouped into a new "mode" rather than released one by one in isolation.
-
-You can't opt into Concurrent Mode on a per-subtree basis. Instead, to opt in, you have to do it in the place where today you call `ReactDOM.render()`.
-
-**This will enable Concurrent Mode for the whole `` tree:**
-
-```js
-import ReactDOM from 'react-dom';
-
-// If you previously had:
-//
-// ReactDOM.render(, document.getElementById('root'));
-//
-// You can opt into Concurrent Mode by writing:
-
-ReactDOM.unstable_createRoot(
- document.getElementById('root')
-).render();
-```
-
->Note:
->
->Concurrent Mode APIs such as `createRoot` only exist in the experimental builds of React.
-
-In Concurrent Mode, the lifecycle methods [previously marked](/blog/2018/03/27/update-on-async-rendering.html) as "unsafe" actually *are* unsafe, and lead to bugs even more than in today's React. We don't recommend trying Concurrent Mode until your app is [Strict Mode](/docs/strict-mode.html)-compatible.
-
-## What to Expect {#what-to-expect}
-
-If you have a large existing app, or if your app depends on a lot of third-party packages, please don't expect that you can use the Concurrent Mode immediately. **For example, at Facebook we are using Concurrent Mode for the new website, but we're not planning to enable it on the old website.** This is because our old website still uses unsafe lifecycle methods in the product code, incompatible third-party libraries, and patterns that don't work well with the Concurrent Mode.
-
-In our experience, code that uses idiomatic React patterns and doesn't rely on external state management solutions is the easiest to get running in the Concurrent Mode. We will describe common problems we've seen and the solutions to them separately in the coming weeks.
-
-### Migration Step: Blocking Mode {#migration-step-blocking-mode}
-
-For older codebases, Concurrent Mode might be a step too far. This is why we also provide a new "Blocking Mode" in the experimental React builds. You can try it by substituting `createRoot` with `createBlockingRoot`. It only offers a *small subset* of the Concurrent Mode features, but it is closer to how React works today and can serve as a migration step.
-
-To recap:
-
-* **Legacy Mode:** `ReactDOM.render(, rootNode)`. This is what React apps use today. There are no plans to remove the legacy mode in the observable future — but it won't be able to support these new features.
-* **Blocking Mode:** `ReactDOM.createBlockingRoot(rootNode).render()`. It is currently experimental. It is intended as a first migration step for apps that want to get a subset of Concurrent Mode features.
-* **Concurrent Mode:** `ReactDOM.createRoot(rootNode).render()`. It is currently experimental. In the future, after it stabilizes, we intend to make it the default React mode. This mode enables *all* the new features.
-
-### Why So Many Modes? {#why-so-many-modes}
-
-We think it is better to offer a [gradual migration strategy](/docs/faq-versioning.html#commitment-to-stability) than to make huge breaking changes — or to let React stagnate into irrelevance.
-
-In practice, we expect that most apps using Legacy Mode today should be able to migrate at least to the Blocking Mode (if not Concurrent Mode). This fragmentation can be annoying for libraries that aim to support all Modes in the short term. However, gradually moving the ecosystem away from the Legacy Mode will also *solve* problems that affect major libraries in the React ecosystem, such as [confusing Suspense behavior when reading layout](https://github.com/facebook/react/issues/14536) and [lack of consistent batching guarantees](https://github.com/facebook/react/issues/15080). There's a number of bugs that can't be fixed in Legacy Mode without changing semantics, but don't exist in Blocking and Concurrent Modes.
-
-You can think of the Blocking Mode as a "gracefully degraded" version of the Concurrent Mode. **As a result, in longer term we should be able to converge and stop thinking about different Modes altogether.** But for now, Modes are an important migration strategy. They let everyone decide when a migration is worth it, and upgrade at their own pace.
-
-### Feature Comparison {#feature-comparison}
-
-
-
-
-
-\*: Legacy mode has automatic batching in React-managed events but it's limited to one browser task. Non-React events must opt-in using `unstable_batchedUpdates`. In Blocking Mode and Concurrent Mode, all `setState`s are batched by default.
-
-\*\*: Warns in development.
diff --git a/content/docs/concurrent-mode-intro.md b/content/docs/concurrent-mode-intro.md
deleted file mode 100644
index 45dbeca7b..000000000
--- a/content/docs/concurrent-mode-intro.md
+++ /dev/null
@@ -1,100 +0,0 @@
----
-id: concurrent-mode-intro
-title: Знайомство з паралельним режимом (Експериментальний)
-permalink: docs/concurrent-mode-intro.html
-next: concurrent-mode-suspense.html
----
-
-
-
-
-
->Увага:
->
->На сторінці описані **експериментальні функції, [яких ще немає](/docs/concurrent-mode-adoption.html) в стабільній версії**. Не використовуйте експериментальні збірки React в продакшн додатках. Ці функції можуть суттєво змінитися та без попередження потрапити в React.
->
->Ця документація орієнтована на першопрохідців та зацікавлених користувачів. **Якщо ви новачок в React, не турбуйтеся про ці функції**, немає необхідності вивчати їх прямо зараз.
-
-
-
-На цій сторінці представлений теоретичний огляд "Паралельного Режиму". **Для більш практичного застосування ви можете ознайомитись з наступними розділами:**
-
-* [Затримка при запиті даних](/docs/concurrent-mode-suspense.html) описує новий механізм запиту даних у React-компонентах.
-* [Патерни паралельного UI](/docs/concurrent-mode-patterns.html) показує деякі патерни UI, які стали можливими завдяки паралельному режиму та затримці.
-* [Використання паралельного режиму](/docs/concurrent-mode-adoption.html) пояснює, як ви можете спробувати паралельний режим у своєму проекті.
-* [Довідник API паралельного режиму](/docs/concurrent-mode-reference.html) документує нові API, доступні в експериментальних версіях.
-
-## Що таке паралельний режим? {#what-is-concurrent-mode}
-
-Паралельний режим — набір нових функцій, які допомагають React додаткам залишатися чутливими та плавно підлаштовується під можливості пристрою користувача та швидкість мережі.
-
-Ці особливості досі експериментальні й можуть змінюватися. Вони ще не є частиною стабільної версії React, але ви можете спробувати їх в експериментальній збірці.
-
-## Блокування проти переривання рендерингу {#blocking-vs-interruptible-rendering}
-
-**Щоб пояснити паралельний режим, ми будемо використовувати контроль версій як метафору.** Якщо ви працюєте в команді, ви, ймовірно, використовуєте систему контролю версій на зразок Git й працюєте з гілками. Коли гілка готова, ви можете злити свою роботу в master, щоб інші люди могли її витягнути.
-
-До того, як створили контроль версій, робочий процес розробки дуже відрізнявся. Там не було поняття гілок. Якщо ви хотіли відредагувати якісь файли, вам доводилося говорити всім не торкатися цих файлів, поки ви не закінчите роботу. Ви навіть не могли почати працювати над ними одночасно з іншою людиною - ви були буквально *заблоковані*.
-
-Це ілюструє як типово сьогодні працюють UI-бібліотеки, включаючи React. Як тільки вони починають рендерити оновлення, включаючи створення нових вузлів DOM та запуск коду всередині компонентів, вони не можуть перервати цю роботу. Цей підхід ми будемо називати "блокуванням рендеренгу".
-
-У паралельному режимі рендеринг не блокується. Він переривається. Це робить користування додатком зручнішим. Він також розблоковує нові функції, які раніше були неможливі. Перш ніж ми розглянемо конкретні приклади в [наступних](/docs/concurrent-mode-suspense.html) [розділах](/docs/concurrent-mode-patterns.html), ми зробимо загальний огляд нових функцій.
-
-### Переривання рендерингу
-
-Розглянемо список продуктів, що фільтруються. Ви коли-небудь фільтрували список та відчували, що він затиняїться при кожному натисканні клавіш? Деяка робота над оновленням списку продуктів може бути неминучою, наприклад, створення нових вузлів DOM або будування макета браузером. Однак *коли* і *як* ми виконуємо цю роботу, грає велику роль.
-
-Поширений спосіб обійти запинання — не обробляти вхідні дані при кожній зміні (debounce). У такому разі ми оновлюємо список лише *після* того, як користувач перестає друкувати. Однак, може бути неприємно, що інтерфейс користувача не оновлюється під час введення тексту. Як альтернатива, ми могли б "гальмувати" (throttle) введення даних та оновлювати список з певною максимальною частотою. Але потім на пристроях з меншою потужністю ми все-таки почнемо затинатися. Обидва підходи створюють неоптимальний UI.
-
-Причина затинання проста: після початку рендеринга, він не може бути перерваний. Тому браузер не може оновити введення тексту відразу після натискання клавіши. Незалежно від того, наскільки добре може виглядати UI-бібліотека (наприклад, React) у порівнянні з іншими, якщо він використовує блокування рендерингу, певна кількість роботи у ваших компонентах завжди призведе до затинання. І найчастіше це не так просто виправити.
-
-**Паралельний режим усуває це фундаментальне обмеження, роблячи рендеринг переривчастим.** Це означає, що коли користувач натискає іншу клавішу, React-у не потрібно блокувати браузер для оновлення введення тексту. Натомість він може дозволити браузеру відобразити оновлення вводу, а потім продовжити оновлювати список *у пам'яті*. Коли рендеринг закінчений, React оновлює DOM, а зміни відображаються на екрані.
-
-Концептуально ви можете думати про це так, що React готує кожне оновлення "на гілці". Так само, як ви можете відмовитися від роботи у гілках або перемикатися між ними, React у паралельному режимі може перервати постійне оновлення, щоб зробити щось важливіше, а потім повернутися до того, що він робив раніше. Ця методика може також нагадувати вам про [подвійну буферизацію](https://wiki.osdev.org/Double_Buffering) у відеоіграх.
-
-Паралельний режим зменьшує потребу в очікуванні (debouncing) та гальмуванні (throttling) в інтерфейсі користувача. Оскільки рендеринг переривається, React не потрібно штучно *затримувати* рендеринг, щоб уникнути затинання. Він може почати рендеринг відразу, але перервати цю роботу, коли це необхідно, щоб додаток завжди був в змозі реагувати на запити.
-
-### Навмисні послідовності завантаження {#intentional-loading-sequences}
-
-Ми вже говорили, що паралельний режим у React — це ніби працювання "на гілці". Гілки корисні не тільки для короткочасних виправлень, але і для довготривалих змін. Іноді ви можете працювати над функцією, але може пройти кілька тижнів, перш ніж вона виявиться в «досить хорошому стані», щоб злитися з master. Цей аспект метафори про управління версіями стосується і рендерингу.
-
-Уявіть, що ми пересуваємося між двома екранами в додатку. Іноді у нас може не вистачати завантаженого коду і даних, щоб показати користувачеві «досить добрий» стан завантаження на новому екрані. Перехід на порожній екран або на великий спінер може бути неприємним досвідом. Проте найчастіше, щоб отримати необхідний код та дані непотрібно занадто багато часу. **Чи не було б приємніше, якби React міг залишитися на старому екрані трохи довше і "пропустити" "поганий стан завантаження" перед тим, як показати новий екран?**
-
-Незважаючи на те, що це можно робити і сьогодні, це важко організувати. У паралельному режимі ця функція вбудована. React спочатку починає готувати новий екран в пам'яті - або, як йдеться у нашій метафорі, "на іншій гілці". Тож React може зачекати, перш ніж оновити DOM, щоб завантажувати більше контенту. У паралельному режимі ми можемо сказати React продовжувати показувати старий екран, повністю інтерактивний, із вбудованим індикатором завантаження. І коли новий екран буде готовий, React може перевести нас до нього.
-
-### Паралельність {#concurrency}
-
-Давайте резюмуємо два приклади, наведені вище, і подивимося, як паралельний режим об'єднує їх: **У паралельному режимі React може працювати над кількома оновленнями стану *паралельно*** - так само, як гілки дозволяють різним членам команди працювати самостійно:
-
-* Для оновлень пов'язаних до ЦП (наприклад, створення вузлів DOM та запуску коду компонента) паралельність означає, що більш термінове оновлення може «перервати» рендеринг, що вже розпочався.
-* Для оновлень пов'язаних до вводу-виводу (таких як отримання кода або даних з мережі), паралельність означає, що React може почати візуалізацію в пам'яті ще до того, як всі дані надійдуть, і пропустити показ порожніх станів завантаження.
-
-Важливо, те, що ви *використовуєте* React так само. Поняття, такі як компоненти, реквізити та стан, принципово працюють однаково. Коли ви хочете оновити екран, ви встановлюєте стан.
-
-React використовує евристику, щоб вирішити, наскільки "терміновим" є оновлення, і дозволяє вам налаштувати його за допомогою декількох рядків коду, щоб ви могли досягти бажаного досвіду користувача для кожної взаємодії.
-
-## Досвід впровадження у продакшн {#putting-research-into-production}
-
-Існує загальна тема щодо можливості паралельного режиму. **Його місія полягає в тому, щоб допомогти інтегрувати результати від дослідження взаємодії людини і комп'ютера в реальному UI.**
-
-Наприклад, дослідження показують, що відображення занадто багатьох станів проміжного завантаження при переході між екранами робить відчуття перехіду *повільніше*. Ось чому паралельний режим показує нові стани завантаження за фіксованим "графіком", щоб уникнути нестабільності та занадто частого оновлення.
-
-Аналогічно, з досліджень ми знаємо, що з такі взаємодії, як наведення курсора та введення тексту, потрібно обробляти за дуже короткий проміжок часу, тоді як кліки та переходи сторінок можуть зачекати трохи довше, не відчуваючи лага. Різні "пріоритети", які використовує паралельний режим, приблизно відповідають категоріям взаємодії в дослідженні людського сприйняття.
-
-Команди з сильним фокусом на досвіді користувачів іноді вирішують подібні проблеми одноразовими рішеннями. Однак ці рішення рідко виживають довгий час, оскільки їх важко підтримувати. У паралельному режимі наша мета полягає в тому, щоб визначити результати досліджень інтерфейсу в самій абстракції та надати ідіоматичні способи їх використання. Як UI-бібліотека, React чудово підходить для цього.
-
-## Наступні кроки {#next-steps}
-
-Тепер ви знаєте, що таке паралельний режим!
-
-На наступних сторінках ви дізнаєтесь більше деталей щодо конкретних тем:
-
-* [Затримка при запиті даних](/docs/concurrent-mode-suspense.html) описує новий механізм запиту даних у React-компонентах.
-* [Патерни паралельного UI](/docs/concurrent-mode-patterns.html) показує деякі патерни UI, які стали можливими завдяки паралельному режиму та затримці.
-* [Використання паралельного режиму](/docs/concurrent-mode-adoption.html) пояснює, як ви можете спробувати паралельний режим у своєму проекті.
-* [Довідник API паралельного режиму](/docs/concurrent-mode-reference.html) документує нові API, доступні в експериментальних версіях.
diff --git a/content/docs/concurrent-mode-patterns.md b/content/docs/concurrent-mode-patterns.md
deleted file mode 100644
index f591c97b9..000000000
--- a/content/docs/concurrent-mode-patterns.md
+++ /dev/null
@@ -1,937 +0,0 @@
----
-id: concurrent-mode-patterns
-title: Concurrent UI Patterns (Experimental)
-permalink: docs/concurrent-mode-patterns.html
-prev: concurrent-mode-suspense.html
-next: concurrent-mode-adoption.html
----
-
-
-
-
-
->Caution:
->
->This page describes **experimental features that are [not yet available](/docs/concurrent-mode-adoption.html) in a stable release**. Don't rely on experimental builds of React in production apps. These features may change significantly and without a warning before they become a part of React.
->
->This documentation is aimed at early adopters and people who are curious. **If you're new to React, don't worry about these features** -- you don't need to learn them right now. For example, if you're looking for a data fetching tutorial that works today, read [this article](https://www.robinwieruch.de/react-hooks-fetch-data/) instead.
-
-
-
-Usually, when we update the state, we expect to see changes on the screen immediately. This makes sense because we want to keep our app responsive to user input. However, there are cases where we might prefer to **defer an update from appearing on the screen**.
-
-For example, if we switch from one page to another, and none of the code or data for the next screen has loaded yet, it might be frustrating to immediately see a blank page with a loading indicator. We might prefer to stay longer on the previous screen. Implementing this pattern has historically been difficult in React. Concurrent Mode offers a new set of tools to do that.
-
-- [Transitions](#transitions)
- - [Wrapping setState in a Transition](#wrapping-setstate-in-a-transition)
- - [Adding a Pending Indicator](#adding-a-pending-indicator)
- - [Reviewing the Changes](#reviewing-the-changes)
- - [Where Does the Update Happen?](#where-does-the-update-happen)
- - [Transitions Are Everywhere](#transitions-are-everywhere)
- - [Baking Transitions Into the Design System](#baking-transitions-into-the-design-system)
-- [The Three Steps](#the-three-steps)
- - [Default: Receded → Skeleton → Complete](#default-receded-skeleton-complete)
- - [Preferred: Pending → Skeleton → Complete](#preferred-pending-skeleton-complete)
- - [Wrap Lazy Features in ``](#wrap-lazy-features-in-suspense)
- - [Suspense Reveal “Train”](#suspense-reveal-train)
- - [Delaying a Pending Indicator](#delaying-a-pending-indicator)
- - [Recap](#recap)
-- [Other Patterns](#other-patterns)
- - [Splitting High and Low Priority State](#splitting-high-and-low-priority-state)
- - [Deferring a Value](#deferring-a-value)
- - [SuspenseList](#suspenselist)
-- [Next Steps](#next-steps)
-
-## Transitions {#transitions}
-
-Let's revisit [this demo](https://codesandbox.io/s/infallible-feather-xjtbu) from the previous page about [Suspense for Data Fetching](/docs/concurrent-mode-suspense.html).
-
-When we click the "Next" button to switch the active profile, the existing page data immediately disappears, and we see the loading indicator for the whole page again. We can call this an "undesirable" loading state. **It would be nice if we could "skip" it and wait for some content to load before transitioning to the new screen.**
-
-React offers a new built-in `useTransition()` Hook to help with this.
-
-We can use it in three steps.
-
-First, we'll make sure that we're actually using Concurrent Mode. We'll talk more about [adopting Concurrent Mode](/docs/concurrent-mode-adoption.html) later, but for now it's sufficient to know that we need to use `ReactDOM.createRoot()` rather than `ReactDOM.render()` for this feature to work:
-
-```js
-const rootElement = document.getElementById("root");
-// Opt into Concurrent Mode
-ReactDOM.createRoot(rootElement).render();
-```
-
-Next, we'll add an import for the `useTransition` Hook from React:
-
-```js
-import React, { useState, useTransition, Suspense } from "react";
-```
-
-Finally, we'll use it inside the `App` component:
-
-```js{3-5}
-function App() {
- const [resource, setResource] = useState(initialResource);
- const [startTransition, isPending] = useTransition({
- timeoutMs: 3000
- });
- // ...
-```
-
-**By itself, this code doesn't do anything yet.** We will need to use this Hook's return values to set up our state transition. There are two values returned from `useTransition`:
-
-* `startTransition` is a function. We'll use it to tell React *which* state update we want to defer.
-* `isPending` is a boolean. It's React telling us whether that transition is ongoing at the moment.
-
-We will use them right below.
-
-Note we passed a configuration object to `useTransition`. Its `timeoutMs` property specifies **how long we're willing to wait for the transition to finish**. By passing `{timeoutMs: 3000}`, we say "If the next profile takes more than 3 seconds to load, show the big spinner -- but before that timeout it's okay to keep showing the previous screen".
-
-### Wrapping setState in a Transition {#wrapping-setstate-in-a-transition}
-
-Our "Next" button click handler sets the state that switches the current profile in the state:
-
-```js{4}
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/brave-villani-ypxvf)**
-
-Notice how when you type into the input, the `` component suspends, and we see the `
Loading...
` fallback until we get fresh results. This is not ideal. It would be better if we could see the *previous* translation for a bit while we're fetching the next one.
-
-In fact, if we open the console, we'll see a warning:
-
-```
-Warning: App triggered a user-blocking update that suspended.
-
-The fix is to split the update into multiple parts: a user-blocking update to provide immediate feedback, and another update that triggers the bulk of the changes.
-
-Refer to the documentation for useTransition to learn how to implement this pattern.
-```
-
-As we mentioned earlier, if some state update causes a component to suspend, that state update should be wrapped in a transition. Let's add `useTransition` to our component:
-
-```js{4-6,10,13}
-function App() {
- const [query, setQuery] = useState(initialQuery);
- const [resource, setResource] = useState(initialResource);
- const [startTransition, isPending] = useTransition({
- timeoutMs: 5000
- });
-
- function handleChange(e) {
- const value = e.target.value;
- startTransition(() => {
- setQuery(value);
- setResource(fetchTranslation(value));
- });
- }
-
- // ...
-
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/zen-keldysh-rifos)**
-
-Try typing into the input now. Something's wrong! The input is updating very slowly.
-
-We've fixed the first problem (suspending outside of a transition). But now because of the transition, our state doesn't update immediately, and it can't "drive" a controlled input!
-
-The answer to this problem **is to split the state in two parts:** a "high priority" part that updates immediately, and a "low priority" part that may wait for a transition.
-
-In our example, we already have two state variables. The input text is in `query`, and we read the translation from `resource`. We want changes to the `query` state to happen immediately, but changes to the `resource` (i.e. fetching a new translation) should trigger a transition.
-
-So the correct fix is to put `setQuery` (which doesn't suspend) *outside* the transition, but `setResource` (which will suspend) *inside* of it.
-
-```js{4,5}
-function handleChange(e) {
- const value = e.target.value;
-
- // Outside the transition (urgent)
- setQuery(value);
-
- startTransition(() => {
- // Inside the transition (may be delayed)
- setResource(fetchTranslation(value));
- });
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/lively-smoke-fdf93)**
-
-With this change, it works as expected. We can type into the input immediately, and the translation later "catches up" to what we have typed.
-
-### Deferring a Value {#deferring-a-value}
-
-By default, React always renders a consistent UI. Consider code like this:
-
-```js
-<>
-
-
->
-```
-
-React guarantees that whenever we look at these components on the screen, they will reflect data from the same `user`. If a different `user` is passed down because of a state update, you would see them changing together. You can't ever record a screen and find a frame where they would show values from different `user`s. (If you ever run into a case like this, file a bug!)
-
-This makes sense in the vast majority of situations. Inconsistent UI is confusing and can mislead users. (For example, it would be terrible if a messenger's Send button and the conversation picker pane "disagreed" about which thread is currently selected.)
-
-However, sometimes it might be helpful to intentionally introduce an inconsistency. We could do it manually by "splitting" the state like above, but React also offers a built-in Hook for this:
-
-```js
-import { useDeferredValue } from 'react';
-
-const deferredValue = useDeferredValue(value, {
- timeoutMs: 5000
-});
-```
-
-To demonstrate this feature, we'll use [the profile switcher example](https://codesandbox.io/s/musing-ramanujan-bgw2o). Click the "Next" button and notice how it takes 1 second to do a transition.
-
-Let's say that fetching the user details is very fast and only takes 300 milliseconds. Currently, we're waiting a whole second because we need both user details and posts to display a consistent profile page. But what if we want to show the details faster?
-
-If we're willing to sacrifice consistency, we could **pass potentially stale data to the components that delay our transition**. That's what `useDeferredValue()` lets us do:
-
-```js{2-4,10,11,21}
-function ProfilePage({ resource }) {
- const deferredResource = useDeferredValue(resource, {
- timeoutMs: 1000
- });
- return (
- Loading profile...}>
-
- Loading posts...}>
-
-
-
- );
-}
-
-function ProfileTimeline({ isStale, resource }) {
- const posts = resource.posts.read();
- return (
-
- {posts.map(post => (
-
{post.text}
- ))}
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/vigorous-keller-3ed2b)**
-
-The tradeoff we're making here is that `` will be inconsistent with other components and potentially show an older item. Click "Next" a few times, and you'll notice it. But thanks to that, we were able to cut down the transition time from 1000ms to 300ms.
-
-Whether or not it's an appropriate tradeoff depends on the situation. But it's a handy tool, especially when the content doesn't change noticeably between items, and the user might not even realize they were looking at a stale version for a second.
-
-It's worth noting that `useDeferredValue` is not *only* useful for data fetching. It also helps when an expensive component tree causes an interaction (e.g. typing in an input) to be sluggish. Just like we can "defer" a value that takes too long to fetch (and show its old value despite other components updating), we can do this with trees that take too long to render.
-
-For example, consider a filterable list like this:
-
-```js
-function App() {
- const [text, setText] = useState("hello");
-
- function handleChange(e) {
- setText(e.target.value);
- }
-
- return (
-
-
- ...
-
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/pensive-shirley-wkp46)**
-
-In this example, **every item in `` has an artificial slowdown -- each of them blocks the thread for a few milliseconds**. We'd never do this in a real app, but this helps us simulate what can happen in a deep component tree with no single obvious place to optimize.
-
-We can see how typing in the input causes stutter. Now let's add `useDeferredValue`:
-
-```js{3-5,18}
-function App() {
- const [text, setText] = useState("hello");
- const deferredText = useDeferredValue(text, {
- timeoutMs: 5000
- });
-
- function handleChange(e) {
- setText(e.target.value);
- }
-
- return (
-
-
- ...
-
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/infallible-dewdney-9fkv9)**
-
-Now typing has a lot less stutter -- although we pay for this by showing the results with a lag.
-
-How is this different from debouncing? Our example has a fixed artificial delay (3ms for every one of 80 items), so there is always a delay, no matter how fast our computer is. However, the `useDeferredValue` value only "lags behind" if the rendering takes a while. There is no minimal lag imposed by React. With a more realistic workload, you can expect the lag to adjust to the user’s device. On fast machines, the lag would be smaller or non-existent, and on slow machines, it would be more noticeable. In both cases, the app would remain responsive. That’s the advantage of this mechanism over debouncing or throttling, which always impose a minimal delay and can't avoid blocking the thread while rendering.
-
-Even though there is an improvement in responsiveness, this example isn't as compelling yet because Concurrent Mode is missing some crucial optimizations for this use case. Still, it is interesting to see that features like `useDeferredValue` (or `useTransition`) are useful regardless of whether we're waiting for network or for computational work to finish.
-
-### SuspenseList {#suspenselist}
-
-`` is the last pattern that's related to orchestrating loading states.
-
-Consider this example:
-
-```js{5-10}
-function ProfilePage({ resource }) {
- return (
- <>
-
- Loading posts...}>
-
-
- Loading fun facts...}>
-
-
- >
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/proud-tree-exg5t)**
-
-The API call duration in this example is randomized. If you keep refreshing it, you will notice that sometimes the posts arrive first, and sometimes the "fun facts" arrive first.
-
-This presents a problem. If the response for fun facts arrives first, we'll see the fun facts below the `
Loading posts...
` fallback for posts. We might start reading them, but then the *posts* response will come back, and shift all the facts down. This is jarring.
-
-One way we could fix it is by putting them both in a single boundary:
-
-```js
-Loading posts and fun facts...}>
-
-
-
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/currying-violet-5jsiy)**
-
-The problem with this is that now we *always* wait for both of them to be fetched. However, if it's the *posts* that came back first, there's no reason to delay showing them. When fun facts load later, they won't shift the layout because they're already below the posts.
-
-Other approaches to this, such as composing Promises in a special way, are increasingly difficult to pull off when the loading states are located in different components down the tree.
-
-To solve this, we will import `SuspenseList`:
-
-```js
-import { SuspenseList } from 'react';
-```
-
-`` coordinates the "reveal order" of the closest `` nodes below it:
-
-```js{3,11}
-function ProfilePage({ resource }) {
- return (
-
-
- Loading posts...}>
-
-
- Loading fun facts...}>
-
-
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/black-wind-byilt)**
-
-The `revealOrder="forwards"` option means that the closest `` nodes inside this list **will only "reveal" their content in the order they appear in the tree -- even if the data for them arrives in a different order**. `` has other interesting modes: try changing `"forwards"` to `"backwards"` or `"together"` and see what happens.
-
-You can control how many loading states are visible at once with the `tail` prop. If we specify `tail="collapsed"`, we'll see *at most one* fallback at a time. You can play with it [here](https://codesandbox.io/s/adoring-almeida-1zzjh).
-
-Keep in mind that `` is composable, like anything in React. For example, you can create a grid by putting several `` rows inside a `` table.
-
-## Next Steps {#next-steps}
-
-Concurrent Mode offers a powerful UI programming model and a set of new composable primitives to help you orchestrate delightful user experiences.
-
-It's a result of several years of research and development, but it's not finished. In the section on [adopting Concurrent Mode](/docs/concurrent-mode-adoption.html), we'll describe how you can try it and what you can expect.
diff --git a/content/docs/concurrent-mode-reference.md b/content/docs/concurrent-mode-reference.md
deleted file mode 100644
index 663af1b3b..000000000
--- a/content/docs/concurrent-mode-reference.md
+++ /dev/null
@@ -1,214 +0,0 @@
----
-id: concurrent-mode-reference
-title: Concurrent Mode API Reference (Experimental)
-permalink: docs/concurrent-mode-reference.html
-prev: concurrent-mode-adoption.html
----
-
-
-
-
-
->Caution:
->
->This page describes **experimental features that are [not yet available](/docs/concurrent-mode-adoption.html) in a stable release**. Don't rely on experimental builds of React in production apps. These features may change significantly and without a warning before they become a part of React.
->
->This documentation is aimed at early adopters and people who are curious. **If you're new to React, don't worry about these features** -- you don't need to learn them right now.
-
-
-
-This page is an API reference for the React [Concurrent Mode](/docs/concurrent-mode-intro.html). If you're looking for a guided introduction instead, check out [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html).
-
-**Note: This is a Community Preview and not the final stable version. There will likely be future changes to these APIs. Use at your own risk!**
-
-- [Enabling Concurrent Mode](#concurrent-mode)
- - [`createRoot`](#createroot)
- - [`createBlockingRoot`](#createblockingroot)
-- [Suspense](#suspense)
- - [`Suspense`](#suspensecomponent)
- - [`SuspenseList`](#suspenselist)
- - [`useTransition`](#usetransition)
- - [`useDeferredValue`](#usedeferredvalue)
-
-## Enabling Concurrent Mode {#concurrent-mode}
-
-### `createRoot` {#createroot}
-
-```js
-ReactDOM.createRoot(rootNode).render();
-```
-
-Replaces `ReactDOM.render(, rootNode)` and enables Concurrent Mode.
-
-For more information on Concurrent Mode, check out the [Concurrent Mode documentation.](/docs/concurrent-mode-intro.html)
-
-### `createBlockingRoot` {#createblockingroot}
-
-```js
-ReactDOM.createBlockingRoot(rootNode).render()
-```
-
-Replaces `ReactDOM.render(, rootNode)` and enables [Blocking Mode](/docs/concurrent-mode-adoption.html#migration-step-blocking-mode).
-
-Opting into Concurrent Mode introduces semantic changes to how React works. This means that you can't use Concurrent Mode in just a few components. Because of this, some apps may not be able to migrate directly to Concurrent Mode.
-
-Blocking Mode only contains a small subset of Concurrent Mode features and is intended as an intermediary migration step for apps that are unable to migrate directly.
-
-## Suspense API {#suspense}
-
-### `Suspense` {#suspensecomponent}
-
-```js
-Loading...}>
-
-
-
-```
-
-`Suspense` lets your components "wait" for something before they can render, showing a fallback while waiting.
-
-In this example, `ProfileDetails` is waiting for an asynchronous API call to fetch some data. While we wait for `ProfileDetails` and `ProfilePhoto`, we will show the `Loading...` fallback instead. It is important to note that until all children inside `` has loaded, we will continue to show the fallback.
-
-`Suspense` takes two props:
-* **fallback** takes a loading indicator. The fallback is shown until all of the children of the `Suspense` component have finished rendering.
-* **unstable_avoidThisFallback** takes a boolean. It tells React whether to "skip" revealing this boundary during the initial load. This API will likely be removed in a future release.
-
-### `` {#suspenselist}
-
-```js
-
-
-
-
-
-
-
-
-
-
- ...
-
-```
-
-`SuspenseList` helps coordinate many components that can suspend by orchestrating the order in which these components are revealed to the user.
-
-When multiple components need to fetch data, this data may arrive in an unpredictable order. However, if you wrap these items in a `SuspenseList`, React will not show an item in the list until previous items have been displayed (this behavior is adjustable).
-
-`SuspenseList` takes two props:
-* **revealOrder (forwards, backwards, together)** defines the order in which the `SuspenseList` children should be revealed.
- * `together` reveals *all* of them when they're ready instead of one by one.
-* **tail (collapsed, hidden)** dictates how unloaded items in a `SuspenseList` is shown.
- * By default, `SuspenseList` will show all fallbacks in the list.
- * `collapsed` shows only the next fallback in the list.
- * `hidden` doesn't show any unloaded items.
-
-Note that `SuspenseList` only operates on the closest `Suspense` and `SuspenseList` components below it. It does not search for boundaries deeper than one level. However, it is possible to nest multiple `SuspenseList` components in each other to build grids.
-
-### `useTransition` {#usetransition}
-
-```js
-const SUSPENSE_CONFIG = { timeoutMs: 2000 };
-
-const [startTransition, isPending] = useTransition(SUSPENSE_CONFIG);
-```
-
-`useTransition` allows components to avoid undesirable loading states by waiting for content to load before **transitioning to the next screen**. It also allows components to defer slower, data fetching updates until subsequent renders so that more crucial updates can be rendered immediately.
-
-The `useTransition` hook returns two values in an array.
-* `startTransition` is a function that takes a callback. We can use it to tell React which state we want to defer.
-* `isPending` is a boolean. It's React's way of informing us whether we're waiting for the transition to finish.
-
-**If some state update causes a component to suspend, that state update should be wrapped in a transition.**
-
-```js
-const SUSPENSE_CONFIG = { timeoutMs: 2000 };
-
-function App() {
- const [resource, setResource] = useState(initialResource);
- const [startTransition, isPending] = useTransition(SUSPENSE_CONFIG);
- return (
- <>
- {
- startTransition(() => {
- const nextUserId = getNextId(resource.userId);
- setResource(fetchProfileData(nextUserId));
- });
- }}
- >
- Next
-
- {isPending ? " Loading..." : null}
- }>
-
-
- >
- );
-}
-```
-
-In this code, we've wrapped our data fetching with `startTransition`. This allows us to start fetching the profile data right away, while deferring the render of the next profile page and its associated `Spinner` for 2 seconds (the time shown in `timeoutMs`).
-
-The `isPending` boolean lets React know that our component is transitioning, so we are able to let the user know this by showing some loading text on the previous profile page.
-
-**For an in-depth look at transitions, you can read [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html#transitions).**
-
-#### useTransition Config {#usetransition-config}
-
-```js
-const SUSPENSE_CONFIG = { timeoutMs: 2000 };
-```
-
-`useTransition` accepts an **optional Suspense Config** with a `timeoutMs`. This timeout (in milliseconds) tells React how long to wait before showing the next state (the new Profile Page in the above example).
-
-**Note: We recommend that you share Suspense Config between different modules.**
-
-
-### `useDeferredValue` {#usedeferredvalue}
-
-```js
-const deferredValue = useDeferredValue(value, { timeoutMs: 2000 });
-```
-
-Returns a deferred version of the value that may "lag behind" it for at most `timeoutMs`.
-
-This is commonly used to keep the interface responsive when you have something that renders immediately based on user input and something that needs to wait for a data fetch.
-
-A good example of this is a text input.
-
-```js
-function App() {
- const [text, setText] = useState("hello");
- const deferredText = useDeferredValue(text, { timeoutMs: 2000 });
-
- return (
-
- {/* Keep passing the current text to the input */}
-
- ...
- {/* But the list is allowed to "lag behind" when necessary */}
-
-
- );
- }
-```
-
-This allows us to start showing the new text for the `input` immediately, which allows the webpage to feel responsive. Meanwhile, `MySlowList` "lags behind" for up to 2 seconds according to the `timeoutMs` before updating, allowing it to render with the current text in the background.
-
-**For an in-depth look at deferring values, you can read [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html#deferring-a-value).**
-
-#### useDeferredValue Config {#usedeferredvalue-config}
-
-```js
-const SUSPENSE_CONFIG = { timeoutMs: 2000 };
-```
-
-`useDeferredValue` accepts an **optional Suspense Config** with a `timeoutMs`. This timeout (in milliseconds) tells React how long the deferred value is allowed to lag behind.
-
-React will always try to use a shorter lag when network and device allows it.
diff --git a/content/docs/concurrent-mode-suspense.md b/content/docs/concurrent-mode-suspense.md
deleted file mode 100644
index 12ad112b2..000000000
--- a/content/docs/concurrent-mode-suspense.md
+++ /dev/null
@@ -1,736 +0,0 @@
----
-id: concurrent-mode-suspense
-title: Suspense for Data Fetching (Experimental)
-permalink: docs/concurrent-mode-suspense.html
-prev: concurrent-mode-intro.html
-next: concurrent-mode-patterns.html
----
-
-
-
-
-
->Caution:
->
->This page describes **experimental features that are [not yet available](/docs/concurrent-mode-adoption.html) in a stable release**. Don't rely on experimental builds of React in production apps. These features may change significantly and without a warning before they become a part of React.
->
->This documentation is aimed at early adopters and people who are curious. **If you're new to React, don't worry about these features** -- you don't need to learn them right now. For example, if you're looking for a data fetching tutorial that works today, read [this article](https://www.robinwieruch.de/react-hooks-fetch-data/) instead.
-
-
-
-React 16.6 added a `` component that lets you "wait" for some code to load and declaratively specify a loading state (like a spinner) while we're waiting:
-
-```jsx
-const ProfilePage = React.lazy(() => import('./ProfilePage')); // Lazy-loaded
-
-// Show a spinner while the profile is loading
-}>
-
-
-```
-
-Suspense for Data Fetching is a new feature that lets you also use `` to **declaratively "wait" for anything else, including data.** This page focuses on the data fetching use case, but it can also wait for images, scripts, or other asynchronous work.
-
-- [What Is Suspense, Exactly?](#what-is-suspense-exactly)
- - [What Suspense Is Not](#what-suspense-is-not)
- - [What Suspense Lets You Do](#what-suspense-lets-you-do)
-- [Using Suspense in Practice](#using-suspense-in-practice)
- - [What If I Don’t Use Relay?](#what-if-i-dont-use-relay)
- - [For Library Authors](#for-library-authors)
-- [Traditional Approaches vs Suspense](#traditional-approaches-vs-suspense)
- - [Approach 1: Fetch-on-Render (not using Suspense)](#approach-1-fetch-on-render-not-using-suspense)
- - [Approach 2: Fetch-Then-Render (not using Suspense)](#approach-2-fetch-then-render-not-using-suspense)
- - [Approach 3: Render-as-You-Fetch (using Suspense)](#approach-3-render-as-you-fetch-using-suspense)
-- [Start Fetching Early](#start-fetching-early)
- - [We’re Still Figuring This Out](#were-still-figuring-this-out)
-- [Suspense and Race Conditions](#suspense-and-race-conditions)
- - [Race Conditions with useEffect](#race-conditions-with-useeffect)
- - [Race Conditions with componentDidUpdate](#race-conditions-with-componentdidupdate)
- - [The Problem](#the-problem)
- - [Solving Race Conditions with Suspense](#solving-race-conditions-with-suspense)
-- [Handling Errors](#handling-errors)
-- [Next Steps](#next-steps)
-
-## What Is Suspense, Exactly? {#what-is-suspense-exactly}
-
-Suspense lets your components "wait" for something before they can render. In [this example](https://codesandbox.io/s/frosty-hermann-bztrp), two components wait for an asynchronous API call to fetch some data:
-
-```js
-const resource = fetchProfileData();
-
-function ProfilePage() {
- return (
- Loading profile...}>
-
- Loading posts...}>
-
-
-
- );
-}
-
-function ProfileDetails() {
- // Try to read user info, although it might not have loaded yet
- const user = resource.user.read();
- return
{user.name}
;
-}
-
-function ProfileTimeline() {
- // Try to read posts, although they might not have loaded yet
- const posts = resource.posts.read();
- return (
-
- {posts.map(post => (
-
{post.text}
- ))}
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/frosty-hermann-bztrp)**
-
-This demo is a teaser. Don't worry if it doesn't quite make sense yet. We'll talk more about how it works below. Keep in mind that Suspense is more of a *mechanism*, and particular APIs like `fetchProfileData()` or `resource.posts.read()` in the above example are not very important. If you're curious, you can find their definitions right in the [demo sandbox](https://codesandbox.io/s/frosty-hermann-bztrp).
-
-Suspense is not a data fetching library. It's a **mechanism for data fetching libraries** to communicate to React that *the data a component is reading is not ready yet*. React can then wait for it to be ready and update the UI. At Facebook, we use Relay and its [new Suspense integration](https://relay.dev/docs/en/experimental/step-by-step). We expect that other libraries like Apollo can provide similar integrations.
-
-In the long term, we intend Suspense to become the primary way to read asynchronous data from components -- no matter where that data is coming from.
-
-### What Suspense Is Not {#what-suspense-is-not}
-
-Suspense is significantly different from existing approaches to these problems, so reading about it for the first time often leads to misconceptions. Let's clarify the most common ones:
-
- * **It is not a data fetching implementation.** It does not assume that you use GraphQL, REST, or any other particular data format, library, transport, or protocol.
-
- * **It is not a ready-to-use client.** You can't "replace" `fetch` or Relay with Suspense. But you can use a library that's integrated with Suspense (for example, [new Relay APIs](https://relay.dev/docs/en/experimental/api-reference)).
-
- * **It does not couple data fetching to the view layer.** It helps orchestrate displaying the loading states in your UI, but it doesn't tie your network logic to React components.
-
-### What Suspense Lets You Do {#what-suspense-lets-you-do}
-
-So what's the point of Suspense? There are a few ways we can answer this:
-
-* **It lets data fetching libraries deeply integrate with React.** If a data fetching library implements Suspense support, using it from React components feels very natural.
-
-* **It lets you orchestrate intentionally designed loading states.** It doesn't say _how_ the data is fetched, but it lets you closely control the visual loading sequence of your app.
-
-* **It helps you avoid race conditions.** Even with `await`, asynchronous code is often error-prone. Suspense feels more like reading data *synchronously* — as if it were already loaded.
-
-## Using Suspense in Practice {#using-suspense-in-practice}
-
-At Facebook, so far we have only used the Relay integration with Suspense in production. **If you're looking for a practical guide to get started today, [check out the Relay Guide](https://relay.dev/docs/en/experimental/step-by-step)!** It demonstrates patterns that have already worked well for us in production.
-
-**The code demos on this page use a "fake" API implementation rather than Relay.** This makes them easier to understand if you're not familiar with GraphQL, but they won't tell you the "right way" to build an app with Suspense. This page is more conceptual and is intended to help you see *why* Suspense works in a certain way, and which problems it solves.
-
-### What If I Don't Use Relay? {#what-if-i-dont-use-relay}
-
-If you don't use Relay today, you might have to wait before you can really try Suspense in your app. So far, it's the only implementation that we tested in production and are confident in.
-
-Over the next several months, many libraries will appear with different takes on Suspense APIs. **If you prefer to learn when things are more stable, you might prefer to ignore this work for now, and come back when the Suspense ecosystem is more mature.**
-
-You can also write your own integration for a data fetching library, if you'd like.
-
-### For Library Authors {#for-library-authors}
-
-We expect to see a lot of experimentation in the community with other libraries. There is one important thing to note for data fetching library authors.
-
-Although it's technically doable, Suspense is **not** currently intended as a way to start fetching data when a component renders. Rather, it lets components express that they're "waiting" for data that is *already being fetched*. **[Building Great User Experiences with Concurrent Mode and Suspense](/blog/2019/11/06/building-great-user-experiences-with-concurrent-mode-and-suspense.html) describes why this matters and how to implement this pattern in practice.**
-
-Unless you have a solution that helps prevent waterfalls, we suggest to prefer APIs that favor or enforce fetching before render. For a concrete example, you can look at how [Relay Suspense API](https://relay.dev/docs/en/experimental/api-reference#usepreloadedquery) enforces preloading. Our messaging about this hasn't been very consistent in the past. Suspense for Data Fetching is still experimental, so you can expect our recommendations to change over time as we learn more from production usage and understand the problem space better.
-
-## Traditional Approaches vs Suspense {#traditional-approaches-vs-suspense}
-
-We could introduce Suspense without mentioning the popular data fetching approaches. However, this makes it more difficult to see which problems Suspense solves, why these problems are worth solving, and how Suspense is different from the existing solutions.
-
-Instead, we'll look at Suspense as a logical next step in a sequence of approaches:
-
-* **Fetch-on-render (for example, `fetch` in `useEffect`):** Start rendering components. Each of these components may trigger data fetching in their effects and lifecycle methods. This approach often leads to "waterfalls".
-* **Fetch-then-render (for example, Relay without Suspense):** Start fetching all the data for the next screen as early as possible. When the data is ready, render the new screen. We can't do anything until the data arrives.
-* **Render-as-you-fetch (for example, Relay with Suspense):** Start fetching all the required data for the next screen as early as possible, and start rendering the new screen *immediately — before we get a network response*. As data streams in, React retries rendering components that still need data until they're all ready.
-
->Note
->
->This is a bit simplified, and in practice solutions tend to use a mix of different approaches. Still, we will look at them in isolation to better contrast their tradeoffs.
-
-To compare these approaches, we'll implement a profile page with each of them.
-
-### Approach 1: Fetch-on-Render (not using Suspense) {#approach-1-fetch-on-render-not-using-suspense}
-
-A common way to fetch data in React apps today is to use an effect:
-
-```js
-// In a function component:
-useEffect(() => {
- fetchSomething();
-}, []);
-
-// Or, in a class component:
-componentDidMount() {
- fetchSomething();
-}
-```
-
-We call this approach "fetch-on-render" because it doesn't start fetching until *after* the component has rendered on the screen. This leads to a problem known as a "waterfall".
-
-Consider these `` and `` components:
-
-```js{4-6,22-24}
-function ProfilePage() {
- const [user, setUser] = useState(null);
-
- useEffect(() => {
- fetchUser().then(u => setUser(u));
- }, []);
-
- if (user === null) {
- return
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/fragrant-glade-8huj6)**
-
-If you run this code and watch the console logs, you'll notice the sequence is:
-
-1. We start fetching user details
-2. We wait...
-3. We finish fetching user details
-4. We start fetching posts
-5. We wait...
-6. We finish fetching posts
-
-If fetching user details takes three seconds, we'll only *start* fetching the posts after three seconds! That's a "waterfall": an unintentional *sequence* that should have been parallelized.
-
-Waterfalls are common in code that fetches data on render. They're possible to solve, but as the product grows, many people prefer to use a solution that guards against this problem.
-
-### Approach 2: Fetch-Then-Render (not using Suspense) {#approach-2-fetch-then-render-not-using-suspense}
-
-Libraries can prevent waterfalls by offering a more centralized way to do data fetching. For example, Relay solves this problem by moving the information about the data a component needs to statically analyzable *fragments*, which later get composed into a single query.
-
-On this page, we don't assume knowledge of Relay, so we won't be using it for this example. Instead, we'll write something similar manually by combining our data fetching methods:
-
-```js
-function fetchProfileData() {
- return Promise.all([
- fetchUser(),
- fetchPosts()
- ]).then(([user, posts]) => {
- return {user, posts};
- })
-}
-```
-
-In this example, `` waits for both requests but starts them in parallel:
-
-```js{1,2,8-13}
-// Kick off fetching as early as possible
-const promise = fetchProfileData();
-
-function ProfilePage() {
- const [user, setUser] = useState(null);
- const [posts, setPosts] = useState(null);
-
- useEffect(() => {
- promise.then(data => {
- setUser(data.user);
- setPosts(data.posts);
- });
- }, []);
-
- if (user === null) {
- return
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/wandering-morning-ev6r0)**
-
-The event sequence now becomes like this:
-
-1. We start fetching user details
-2. We start fetching posts
-3. We wait...
-4. We finish fetching user details
-5. We finish fetching posts
-
-We've solved the previous network "waterfall", but accidentally introduced a different one. We wait for *all* data to come back with `Promise.all()` inside `fetchProfileData`, so now we can't render profile details until the posts have been fetched too. We have to wait for both.
-
-Of course, this is possible to fix in this particular example. We could remove the `Promise.all()` call, and wait for both Promises separately. However, this approach gets progressively more difficult as the complexity of our data and component tree grows. It's hard to write reliable components when arbitrary parts of the data tree may be missing or stale. So fetching all data for the new screen and *then* rendering is often a more practical option.
-
-### Approach 3: Render-as-You-Fetch (using Suspense) {#approach-3-render-as-you-fetch-using-suspense}
-
-In the previous approach, we fetched data before we called `setState`:
-
-1. Start fetching
-2. Finish fetching
-3. Start rendering
-
-With Suspense, we still start fetching first, but we flip the last two steps around:
-
-1. Start fetching
-2. **Start rendering**
-3. **Finish fetching**
-
-**With Suspense, we don't wait for the response to come back before we start rendering.** In fact, we start rendering *pretty much immediately* after kicking off the network request:
-
-```js{2,17,23}
-// This is not a Promise. It's a special object from our Suspense integration.
-const resource = fetchProfileData();
-
-function ProfilePage() {
- return (
- Loading profile...}>
-
- Loading posts...}>
-
-
-
- );
-}
-
-function ProfileDetails() {
- // Try to read user info, although it might not have loaded yet
- const user = resource.user.read();
- return
{user.name}
;
-}
-
-function ProfileTimeline() {
- // Try to read posts, although they might not have loaded yet
- const posts = resource.posts.read();
- return (
-
- {posts.map(post => (
-
{post.text}
- ))}
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/frosty-hermann-bztrp)**
-
-Here's what happens when we render `` on the screen:
-
-1. We've already kicked off the requests in `fetchProfileData()`. It gave us a special "resource" instead of a Promise. In a realistic example, it would be provided by our data library's Suspense integration, like Relay.
-2. React tries to render ``. It returns `` and `` as children.
-3. React tries to render ``. It calls `resource.user.read()`. None of the data is fetched yet, so this component "suspends". React skips over it, and tries rendering other components in the tree.
-4. React tries to render ``. It calls `resource.posts.read()`. Again, there's no data yet, so this component also "suspends". React skips over it too, and tries rendering other components in the tree.
-5. There's nothing left to try rendering. Because `` suspended, React shows the closest `` fallback above it in the tree: `
Loading profile...
`. We're done for now.
-
-This `resource` object represents the data that isn't there yet, but might eventually get loaded. When we call `read()`, we either get the data, or the component "suspends".
-
-**As more data streams in, React will retry rendering, and each time it might be able to progress "deeper".** When `resource.user` is fetched, the `` component will render successfully and we'll no longer need the `
Loading profile...
` fallback. Eventually, we'll get all the data, and there will be no fallbacks on the screen.
-
-This has an interesting implication. Even if we use a GraphQL client that collects all data requirements in a single request, *streaming the response lets us show more content sooner*. Because we render-*as-we-fetch* (as opposed to *after* fetching), if `user` appears in the response earlier than `posts`, we'll be able to "unlock" the outer `` boundary before the response even finishes. We might have missed this earlier, but even the fetch-then-render solution contained a waterfall: between fetching and rendering. Suspense doesn't inherently suffer from this waterfall, and libraries like Relay take advantage of this.
-
-Note how we eliminated the `if (...)` "is loading" checks from our components. This doesn't only remove boilerplate code, but it also simplifies making quick design changes. For example, if we wanted profile details and posts to always "pop in" together, we could delete the `` boundary between them. Or we could make them independent from each other by giving each *its own* `` boundary. Suspense lets us change the granularity of our loading states and orchestrate their sequencing without invasive changes to our code.
-
-## Start Fetching Early {#start-fetching-early}
-
-If you're working on a data fetching library, there's a crucial aspect of Render-as-You-Fetch you don't want to miss. **We kick off fetching _before_ rendering.** Look at this code example closer:
-
-```js
-// Start fetching early!
-const resource = fetchProfileData();
-
-// ...
-
-function ProfileDetails() {
- // Try to read user info
- const user = resource.user.read();
- return
{user.name}
;
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/frosty-hermann-bztrp)**
-
-Note that the `read()` call in this example doesn't *start* fetching. It only tries to read the data that is **already being fetched**. This difference is crucial to creating fast applications with Suspense. We don't want to delay loading data until a component starts rendering. As a data fetching library author, you can enforce this by making it impossible to get a `resource` object without also starting a fetch. Every demo on this page using our "fake API" enforces this.
-
-You might object that fetching "at the top level" like in this example is impractical. What are we going to do if we navigate to another profile's page? We might want to fetch based on props. The answer to this is **we want to start fetching in the event handlers instead**. Here is a simplified example of navigating between user's pages:
-
-```js{1,2,10,11}
-// First fetch: as soon as possible
-const initialResource = fetchProfileData(0);
-
-function App() {
- const [resource, setResource] = useState(initialResource);
- return (
- <>
- {
- const nextUserId = getNextId(resource.userId);
- // Next fetch: when the user clicks
- setResource(fetchProfileData(nextUserId));
- }}>
- Next
-
-
- >
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/infallible-feather-xjtbu)**
-
-With this approach, we can **fetch code and data in parallel**. When we navigate between pages, we don't need to wait for a page's code to load to start loading its data. We can start fetching both code and data at the same time (during the link click), delivering a much better user experience.
-
-This poses a question of how do we know *what* to fetch before rendering the next screen. There are several ways to solve this (for example, by integrating data fetching closer with your routing solution). If you work on a data fetching library, [Building Great User Experiences with Concurrent Mode and Suspense](/blog/2019/11/06/building-great-user-experiences-with-concurrent-mode-and-suspense.html) presents a deep dive on how to accomplish this and why it's important.
-
-### We're Still Figuring This Out {#were-still-figuring-this-out}
-
-Suspense itself as a mechanism is flexible and doesn't have many constraints. Product code needs to be more constrained to ensure no waterfalls, but there are different ways to provide these guarantees. Some questions that we're currently exploring include:
-
-* Fetching early can be cumbersome to express. How do we make it easier to avoid waterfalls?
-* When we fetch data for a page, can the API encourage including data for instant transitions *from* it?
-* What is the lifetime of a response? Should caching be global or local? Who manages the cache?
-* Can Proxies help express lazy-loaded APIs without inserting `read()` calls everywhere?
-* What would the equivalent of composing GraphQL queries look like for arbitrary Suspense data?
-
-Relay has its own answers to some of these questions. There is certainly more than a single way to do it, and we're excited to see what new ideas the React community comes up with.
-
-## Suspense and Race Conditions {#suspense-and-race-conditions}
-
-Race conditions are bugs that happen due to incorrect assumptions about the order in which our code may run. Fetching data in the `useEffect` Hook or in class lifecycle methods like `componentDidUpdate` often leads to them. Suspense can help here, too — let's see how.
-
-To demonstrate the issue, we will add a top-level `` component that renders our `` with a button that lets us **switch between different profiles**:
-
-```js{9-11}
-function getNextId(id) {
- // ...
-}
-
-function App() {
- const [id, setId] = useState(0);
- return (
- <>
- setId(getNextId(id))}>
- Next
-
-
- >
- );
-}
-```
-
-Let's compare how different data fetching strategies deal with this requirement.
-
-### Race Conditions with `useEffect` {#race-conditions-with-useeffect}
-
-First, we'll try a version of our original "fetch in effect" example. We'll modify it to pass an `id` parameter from the `` props to `fetchUser(id)` and `fetchPosts(id)`:
-
-```js{1,5,6,14,19,23,24}
-function ProfilePage({ id }) {
- const [user, setUser] = useState(null);
-
- useEffect(() => {
- fetchUser(id).then(u => setUser(u));
- }, [id]);
-
- if (user === null) {
- return
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/nervous-glade-b5sel)**
-
-Note how we also changed the effect dependencies from `[]` to `[id]` — because we want the effect to re-run when the `id` changes. Otherwise, we wouldn't refetch new data.
-
-If we try this code, it might seem like it works at first. However, if we randomize the delay time in our "fake API" implementation and press the "Next" button fast enough, we'll see from the console logs that something is going very wrong. **Requests from the previous profiles may sometimes "come back" after we've already switched the profile to another ID -- and in that case they can overwrite the new state with a stale response for a different ID.**
-
-This problem is possible to fix (you could use the effect cleanup function to either ignore or cancel stale requests), but it's unintuitive and difficult to debug.
-
-### Race Conditions with `componentDidUpdate` {#race-conditions-with-componentdidupdate}
-
-One might think that this is a problem specific to `useEffect` or Hooks. Maybe if we port this code to classes or use convenient syntax like `async` / `await`, it will solve the problem?
-
-Let's try that:
-
-```js
-class ProfilePage extends React.Component {
- state = {
- user: null,
- };
- componentDidMount() {
- this.fetchData(this.props.id);
- }
- componentDidUpdate(prevProps) {
- if (prevProps.id !== this.props.id) {
- this.fetchData(this.props.id);
- }
- }
- async fetchData(id) {
- const user = await fetchUser(id);
- this.setState({ user });
- }
- render() {
- const { id } = this.props;
- const { user } = this.state;
- if (user === null) {
- return
- );
- }
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/trusting-clarke-8twuq)**
-
-This code is deceptively easy to read.
-
-Unfortunately, neither using a class nor the `async` / `await` syntax helped us solve this problem. This version suffers from exactly the same race conditions, for the same reasons.
-
-### The Problem {#the-problem}
-
-React components have their own "lifecycle". They may receive props or update state at any point in time. However, each asynchronous request *also* has its own "lifecycle". It starts when we kick it off, and finishes when we get a response. The difficulty we're experiencing is "synchronizing" several processes in time that affect each other. This is hard to think about.
-
-### Solving Race Conditions with Suspense {#solving-race-conditions-with-suspense}
-
-Let's rewrite this example again, but using Suspense only:
-
-```js
-const initialResource = fetchProfileData(0);
-
-function App() {
- const [resource, setResource] = useState(initialResource);
- return (
- <>
- {
- const nextUserId = getNextId(resource.userId);
- setResource(fetchProfileData(nextUserId));
- }}>
- Next
-
-
- >
- );
-}
-
-function ProfilePage({ resource }) {
- return (
- Loading profile...}>
-
- Loading posts...}>
-
-
-
- );
-}
-
-function ProfileDetails({ resource }) {
- const user = resource.user.read();
- return
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/infallible-feather-xjtbu)**
-
-In the previous Suspense example, we only had one `resource`, so we held it in a top-level variable. Now that we have multiple resources, we moved it to the ``'s component state:
-
-```js{4}
-const initialResource = fetchProfileData(0);
-
-function App() {
- const [resource, setResource] = useState(initialResource);
-```
-
-When we click "Next", the `` component kicks off a request for the next profile, and passes *that* object down to the `` component:
-
-```js{4,8}
- <>
- {
- const nextUserId = getNextId(resource.userId);
- setResource(fetchProfileData(nextUserId));
- }}>
- Next
-
-
- >
-```
-
-Again, notice that **we're not waiting for the response to set the state. It's the other way around: we set the state (and start rendering) immediately after kicking off a request**. As soon as we have more data, React "fills in" the content inside `` components.
-
-This code is very readable, but unlike the examples earlier, the Suspense version doesn't suffer from race conditions. You might be wondering why. The answer is that in the Suspense version, we don't have to think about *time* as much in our code. Our original code with race conditions needed to set the state *at the right moment later*, or otherwise it would be wrong. But with Suspense, we set the state *immediately* -- so it's harder to mess it up.
-
-## Handling Errors {#handling-errors}
-
-When we write code with Promises, we might use `catch()` to handle errors. How does this work with Suspense, given that we don't *wait* for Promises to start rendering?
-
-With Suspense, handling fetching errors works the same way as handling rendering errors -- you can render an [error boundary](/docs/error-boundaries.html) anywhere to "catch" errors in components below.
-
-First, we'll define an error boundary component to use across our project:
-
-```js
-// Error boundaries currently have to be classes.
-class ErrorBoundary extends React.Component {
- state = { hasError: false, error: null };
- static getDerivedStateFromError(error) {
- return {
- hasError: true,
- error
- };
- }
- render() {
- if (this.state.hasError) {
- return this.props.fallback;
- }
- return this.props.children;
- }
-}
-```
-
-And then we can put it anywhere in the tree to catch errors:
-
-```js{5,9}
-function ProfilePage() {
- return (
- Loading profile...}>
-
- Could not fetch posts.}>
- Loading posts...}>
-
-
-
-
- );
-}
-```
-
-**[Try it on CodeSandbox](https://codesandbox.io/s/adoring-goodall-8wbn7)**
-
-It would catch both rendering errors *and* errors from Suspense data fetching. We can have as many error boundaries as we like but it's best to [be intentional](https://aweary.dev/fault-tolerance-react/) about their placement.
-
-## Next Steps {#next-steps}
-
-We've now covered the basics of Suspense for Data Fetching! Importantly, we now better understand *why* Suspense works this way, and how it fits into the data fetching space.
-
-Suspense answers some questions, but it also poses new questions of its own:
-
-* If some component "suspends", does the app freeze? How to avoid this?
-* What if we want to show a spinner in a different place than "above" the component in a tree?
-* If we intentionally *want* to show an inconsistent UI for a small period of time, can we do that?
-* Instead of showing a spinner, can we add a visual effect like "greying out" the current screen?
-* Why does our [last Suspense example](https://codesandbox.io/s/infallible-feather-xjtbu) log a warning when clicking the "Next" button?
-
-To answer these questions, we will refer to the next section on [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html).
diff --git a/content/docs/conditional-rendering.md b/content/docs/conditional-rendering.md
index 0c113ff1d..29730dda9 100644
--- a/content/docs/conditional-rendering.md
+++ b/content/docs/conditional-rendering.md
@@ -8,6 +8,17 @@ redirect_from:
- "tips/false-in-jsx.html"
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Conditional Rendering](https://react.dev/learn/conditional-rendering)
+
+
+
+
React дозволяє розподілити логіку на окремі компоненти. Ці компоненти можна показувати або ховати в залежності від поточного стану додатку.
Умовний рендеринг у React працює так само, як і умовні вирази працюють в JavaScript. Іноді потрібно пояснити React, як стан впливає на те, які компоненти треба сховати, а які — відрендерити, та як саме. Для цього використовуйте [умовний оператор](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) JavaScript, або вирази подібні до [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else).
@@ -35,11 +46,9 @@ function Greeting(props) {
return ;
}
-ReactDOM.render(
- // Спробуйте замінити значення isLoggedIn на true та подивіться на ефект.
- ,
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+// Спробуйте замінити значення isLoggedIn на true та подивіться на ефект.
+root.render();
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/ZpVxNq?editors=0011)
@@ -110,10 +119,8 @@ class LoginControl extends React.Component {
}
}
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render();
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/QKzAgB?editors=0010)
@@ -140,10 +147,9 @@ function Mailbox(props) {
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render();
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/ozJddz?editors=0010)
@@ -152,6 +158,19 @@ ReactDOM.render(
Отже, якщо умова правдива (`true`), то елемент, який йде безпосередньо після `&&`, з'явиться у виводі. Якщо ж умова помилкова (`false`), React проігнорує та пропустить його.
+Note that returning a falsy expression will still cause the element after `&&` to be skipped but will return the falsy expression. In the example below, `
0
` will be returned by the render method.
+
+```javascript{2,5}
+render() {
+ const count = 0;
+ return (
+
+ {count &&
Messages: {count}
}
+
+ );
+}
+```
+
### Вбудовані умови if-else з тернарним оператором {#inline-if-else-with-conditional-operator}
Іншим методом для умовного рендерингу елементів є використання тернарного оператора [`condition ? true : false`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).
@@ -231,10 +250,8 @@ class Page extends React.Component {
}
}
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render();
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/Xjoqwm?editors=0010)
diff --git a/content/docs/context.md b/content/docs/context.md
index b4e8afe4d..d1e20a25e 100644
--- a/content/docs/context.md
+++ b/content/docs/context.md
@@ -4,6 +4,17 @@ title: Контекст
permalink: docs/context.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Passing Data Deeply with Context](https://react.dev/learn/passing-data-deeply-with-context)
+> - [`useContext`](https://react.dev/reference/react/useContext)
+
+
+
Контекст забезпечує спосіб передавати дані через дерево компонентів без необхідності передавати пропси вручну на кожному рівні.
У типовому додатку React дані передаються зверху вниз (від батьківської до дочірньої компоненти) через пропси, але це може бути громіздким для певних типів реквізитів (наприклад, налаштування локалі, тема інтерфейсу користувача), які потрібні багатьом компонентам програми. Контекст надає спосіб обмінюватися значеннями, подібними до цих, між компонентами без необхідності явно передавати властивість через кожен рівень дерева.
@@ -128,7 +139,7 @@ const MyContext = React.createContext(defaultValue);
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
-Accepts a `value` prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
+The Provider component accepts a `value` prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
All consumers that are descendants of a Provider will re-render whenever the Provider's `value` prop changes. The propagation from Provider to its descendant consumers (including [`.contextType`](#classcontexttype) and [`useContext`](/docs/hooks-reference.html#usecontext)) is not subject to the `shouldComponentUpdate` method, so the consumer is updated even when an ancestor component skips an update.
@@ -162,7 +173,7 @@ class MyClass extends React.Component {
MyClass.contextType = MyContext;
```
-The `contextType` property on a class can be assigned a Context object created by [`React.createContext()`](#reactcreatecontext). This lets you consume the nearest current value of that Context type using `this.context`. You can reference this in any of the lifecycle methods including the render function.
+The `contextType` property on a class can be assigned a Context object created by [`React.createContext()`](#reactcreatecontext). Using this property lets you consume the nearest current value of that Context type using `this.context`. You can reference this in any of the lifecycle methods including the render function.
> Note:
>
@@ -189,7 +200,7 @@ class MyClass extends React.Component {
```
-A React component that subscribes to context changes. This lets you subscribe to a context within a [function component](/docs/components-and-props.html#function-and-class-components).
+A React component that subscribes to context changes. Using this component lets you subscribe to a context within a [function component](/docs/components-and-props.html#function-and-class-components).
Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). The function receives the current context value and returns a React node. The `value` argument passed to the function will be equal to the `value` prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the `value` argument will be equal to the `defaultValue` that was passed to `createContext()`.
diff --git a/content/docs/create-a-new-react-app.md b/content/docs/create-a-new-react-app.md
index d53845e2e..75d2435ac 100644
--- a/content/docs/create-a-new-react-app.md
+++ b/content/docs/create-a-new-react-app.md
@@ -8,6 +8,15 @@ prev: add-react-to-a-website.html
next: cdn-links.html
---
+
+
+>
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> See [Start a New React Project](https://react.dev/learn/start-a-new-react-project) for the recommended ways to create an app.
+
+
+
Для більш комфортної роботи використовуйте вбудований набір інструментів.
Ця сторінка описує декілька популярних наборів інструментів для роботи з React, що допоможуть вам з такими задачами як:
@@ -75,7 +84,7 @@ Create React App не опрацьовує бекенд логіку чи лог
- **[Nx](https://nx.dev/react)** це інструментарій для повноцінної розробки в єдиному репозиторії, який має вбудовану підтримку для React, Next.js, [Express](https://expressjs.com/), та інших.
-- **[Parcel](https://parceljs.org/)** -- швидкий бандлер веб-додатків з нульовою конфігурацією, [який працює з React](https://parceljs.org/recipes.html#react).
+- **[Parcel](https://parceljs.org/)** -- швидкий бандлер веб-додатків з нульовою конфігурацією, [який працює з React](https://parceljs.org/recipes/react/).
- **[Razzle](https://github.com/jaredpalmer/razzle)** -- це фреймворк для серверного рендерингу, що не потребує ніякої конфігурації, але більш гнучкий ніж Next.js.
diff --git a/content/docs/design-principles.md b/content/docs/design-principles.md
index 78a450159..97a6ce91f 100644
--- a/content/docs/design-principles.md
+++ b/content/docs/design-principles.md
@@ -92,7 +92,7 @@ There is an internal joke in the team that React should have been called "Schedu
Providing a good developer experience is important to us.
-For example, we maintain [React DevTools](https://github.com/facebook/react-devtools) which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.
+For example, we maintain [React DevTools](https://github.com/facebook/react/tree/main/packages/react-devtools) which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.
We also try to go an extra mile to provide helpful developer warnings. For example, React warns you in development if you nest tags in a way that the browser doesn't understand, or if you make a common typo in the API. Developer warnings and the related checks are the main reason why the development version of React is slower than the production version.
diff --git a/content/docs/error-boundaries.md b/content/docs/error-boundaries.md
index e0155697a..5664665ae 100644
--- a/content/docs/error-boundaries.md
+++ b/content/docs/error-boundaries.md
@@ -4,6 +4,16 @@ title: Запобіжники
permalink: docs/error-boundaries.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React:
+>
+> - [`React.Component`: Catching rendering errors with an error boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
+
+
+
Раніше помилки JavaScript всередині компонентів призводили до пошкодження внутрішнього стану бібліотеки React та спричиняли [видачу](https://github.com/facebook/react/issues/4026) [незрозумілих](https://github.com/facebook/react/issues/6895) [помилок](https://github.com/facebook/react/issues/8579) під час наступних рендерів. Ці помилки були завжди спричинені попереднью помилкою в коді програми. React не надавав можливості вчасно їх опрацювати в компонентах та не міг відновитися після них.
diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md
index 5a357f952..50bf2ccfc 100644
--- a/content/docs/faq-ajax.md
+++ b/content/docs/faq-ajax.md
@@ -72,7 +72,7 @@ class MyComponent extends React.Component {
return (
{items.map(item => (
-
+
{item.name} {item.price}
))}
@@ -100,7 +100,7 @@ function MyComponent() {
.then(
(result) => {
setIsLoaded(true);
- setItems(result.items);
+ setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
@@ -120,7 +120,7 @@ function MyComponent() {
return (
{items.map(item => (
-
+
{item.name} {item.price}
))}
diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md
index c9cfaba61..4209403bb 100644
--- a/content/docs/faq-functions.md
+++ b/content/docs/faq-functions.md
@@ -41,10 +41,9 @@ class Foo extends Component {
```jsx
class Foo extends Component {
- // Примітка: даний синтаксис знаходиться на стадії розробки і ще не стандартизований.
handleClick = () => {
console.log('Натискання відбулось');
- }
+ };
render() {
return Натисни мене;
}
@@ -152,7 +151,6 @@ const A = 65 // ASCII-код символу
class Alphabet extends React.Component {
constructor(props) {
super(props);
- this.handleClick = this.handleClick.bind(this);
this.state = {
justClicked: null,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
@@ -290,9 +288,6 @@ class Searchbox extends React.Component {
}
handleChange(e) {
- // React розташовує події в пулі, тому значення зчитується перед debounce.
- // Як альтернативу, ми могли б викликати `event.persist()` і передати подію в повному обсязі.
- // Більш детально дана тема розглядається тут: reactjs.org/docs/events.html#event-pooling
this.emitChangeDebounced(e.target.value);
}
diff --git a/content/docs/forms.md b/content/docs/forms.md
index 3ff86e323..42ec164d5 100644
--- a/content/docs/forms.md
+++ b/content/docs/forms.md
@@ -9,6 +9,18 @@ redirect_from:
- "docs/forms-zh-CN.html"
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [``](https://react.dev/reference/react-dom/components/input)
+> - [`
+
У React HTML-елементи форм працюють дещо інакше, ніж інші DOM-елементи, тому що елементи форм від початку мають певний внутрішній стан. Наприклад, в цю HTML-форму можна ввести ім'я:
```html
@@ -31,7 +43,7 @@ redirect_from:
Наприклад, якщо ми хочемо, щоб у прикладі вище після відправлення форми передані дані виводилися у консолі, то ми можемо переписати форму як "керований компонент":
-```javascript{4,10-12,24}
+```javascript{4,10-12,21,24}
class NameForm extends React.Component {
constructor(props) {
super(props);
@@ -275,10 +287,10 @@ this.setState(partialState);
Наступний код це демонструє. (Поле вводу спочатку заблоковане, але стає доступним для редагування після невеликої затримки.)
```javascript
-ReactDOM.render(, mountNode);
+ReactDOM.createRoot(mountNode).render();
setTimeout(function() {
- ReactDOM.render(, mountNode);
+ ReactDOM.createRoot(mountNode).render();
}, 1000);
```
diff --git a/content/docs/forwarding-refs.md b/content/docs/forwarding-refs.md
index caff0623b..c7c65028d 100644
--- a/content/docs/forwarding-refs.md
+++ b/content/docs/forwarding-refs.md
@@ -4,6 +4,17 @@ title: Перенаправлення рефів
permalink: docs/forwarding-refs.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Manipulating the DOM with Refs](https://react.dev/learn/manipulating-the-dom-with-refs)
+> - [`forwardRef`](https://react.dev/reference/react/forwardRef)
+
+
+
Перенаправлення рефів — це техніка для автоматичної передачі [рефа](/docs/refs-and-the-dom.html) від компонента до одного із його дітей. Для більшості компонентів, зазвичай, вона не є необхідною. Тим не менше, може бути корисною в деяких випадках, особливо якщо ви пишете бібліотеку. Давайте розглянемо найбільш поширені сценарії.
## Перенаправлення рефів у DOM-компоненти {#forwarding-refs-to-dom-components}
diff --git a/content/docs/fragments.md b/content/docs/fragments.md
index f8badb428..e758c11cc 100644
--- a/content/docs/fragments.md
+++ b/content/docs/fragments.md
@@ -4,6 +4,16 @@ title: Фрагменти
permalink: docs/fragments.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React:
+>
+> - [``](https://react.dev/reference/react/Fragment)
+
+
+
Повернення кількох елементів з компонента є поширеною практикою в React. Фрагменти дозволяють формувати список дочірніх елементів, не створюючи зайвих вузлів в DOM.
```js
diff --git a/content/docs/getting-started.md b/content/docs/getting-started.md
index 89080c424..dc33a2d5c 100644
--- a/content/docs/getting-started.md
+++ b/content/docs/getting-started.md
@@ -18,6 +18,15 @@ redirect_from:
- "docs/environments.html"
---
+
+
+>
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> The new [Quick Start](https://react.dev/learn) teaches modern React and includes live examples.
+
+
+
В даному розділі ми оглянемо документацію React та пов'язані з ним ресурси.
**React** — це JavaScript-бібліотека для створення інтерфейсів користувача. Відвідайте [нашу головну сторінку](/) або [вступ](/tutorial/tutorial.html), аби скласти перше враження про React.
@@ -38,7 +47,7 @@ redirect_from:
Хочете погратися з React? Скористайтеся онлайн-пісочницями. Спробуйте початковий шаблон на [CodePen](codepen://hello-world), [CodeSandbox](https://codesandbox.io/s/new), [Glitch](https://glitch.com/edit/#!/remix/starter-react-template) або [Stackblitz](https://stackblitz.com/fork/react).
-Віддаєте перевагу вашому улюбленому редактору коду? Тоді ви можете [завантажити даний HTML-файл](https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html), відредагувати та відкрити його у вашому браузері. Даний шаблон трансформує JSX у JavaScript під час запуску . Однак, доволі повільно, тому ми рекомендуємо використовувати даний файл тільки для простих демонстраційних прикладів.
+Віддаєте перевагу вашому улюбленому редактору коду? Тоді ви можете [завантажити даний HTML-файл](https://raw.githubusercontent.com/reactjs/reactjs.org/main/static/html/single-file-example.html), відредагувати та відкрити його у вашому браузері. Даний шаблон трансформує JSX у JavaScript під час запуску . Однак, доволі повільно, тому ми рекомендуємо використовувати даний файл тільки для простих демонстраційних прикладів.
### Додаємо React до сайту {#add-react-to-a-website}
@@ -115,7 +124,7 @@ redirect_from:
Ви також можете підписатись на [профіль @reactjs](https://twitter.com/reactjs) у Twitter, однак ви не пропустите нічого важливого, якщо будете слідкувати тільки за блогом.
-У блозі ми пишемо не про всі релізи React, але завжди є можливість переглянути повний список змін [у файлі `CHANGELOG.md` у репозиторії React](https://github.com/facebook/react/blob/master/CHANGELOG.md), а також на сторінці [Релізи](https://github.com/facebook/react/releases).
+У блозі ми пишемо не про всі релізи React, але завжди є можливість переглянути повний список змін [у файлі `CHANGELOG.md` у репозиторії React](https://github.com/facebook/react/blob/main/CHANGELOG.md), а також на сторінці [Релізи](https://github.com/facebook/react/releases).
## Документація старих версій React {#versioned-documentation}
diff --git a/content/docs/handling-events.md b/content/docs/handling-events.md
index 9bc8bacc8..1d0d6f933 100644
--- a/content/docs/handling-events.md
+++ b/content/docs/handling-events.md
@@ -8,6 +8,16 @@ redirect_from:
- "docs/events-ko-KR.html"
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Responding to Events](https://react.dev/learn/responding-to-events)
+
+
+
Обробка подій для React-елементів дуже схожа до обробки подій для DOM-елементів. Але є деякі синтаксичні відмінності:
* Події React іменуються в camelCase, а не в нижньому регістрі.
* З JSX ви передаєте функцію як обробник події замість рядка.
@@ -31,24 +41,24 @@ redirect_from:
Інша відмінність полягає в тому, що ви не можете повернути `false` для того, щоб запобігти поведінці за замовчуванням у React. Ви маєте явно викликати `preventDefault`. Наприклад, для звичайного HTML, щоб запобігти поведінці посилання за замовчуванням (відкриття нової сторінки) ви можете написати:
```html
-
- Натисни на мене
-
+
```
У React це може виглядати так:
-```js{2-5,8}
-function ActionLink() {
- function handleClick(e) {
+```js{3}
+function Form() {
+ function handleSubmit(e) {
e.preventDefault();
- console.log('Посилання було натиснуте.');
+ console.log('You clicked submit.');
}
return (
-
- Натисни на мене
-
+
);
}
```
@@ -70,8 +80,8 @@ class Toggle extends React.Component {
}
handleClick() {
- this.setState(state => ({
- isToggleOn: !state.isToggleOn
+ this.setState(prevState => ({
+ isToggleOn: !prevState.isToggleOn
}));
}
@@ -83,11 +93,6 @@ class Toggle extends React.Component {
);
}
}
-
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
```
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/xEmzGg?editors=0010)
@@ -101,10 +106,9 @@ ReactDOM.render(
```js{2-6}
class LoggingButton extends React.Component {
// Цей синтаксис забезпечує прив'язку `this` всередині handleClick.
- // Попередження: це *експериментальний* синтаксис.
handleClick = () => {
console.log('this це:', this);
- }
+ };
render() {
return (
diff --git a/content/docs/hello-world.md b/content/docs/hello-world.md
index d666b6228..c3adbb3b0 100644
--- a/content/docs/hello-world.md
+++ b/content/docs/hello-world.md
@@ -2,22 +2,29 @@
id: hello-world
title: Привіт, світе
permalink: docs/hello-world.html
-prev: cdn-links.html
+prev: release-channels.html
next: introducing-jsx.html
---
+
+
+>
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> See [Quick Start](https://react.dev/learn) for an introduction to React.
+
+
+
Найменший приклад React виглядає наступним чином:
-```js
-ReactDOM.render(
-
);
```
На сторінці з'явиться заголовок "Hello, world!"
-[](codepen://hello-world)
+**[Try it on CodePen](https://codepen.io/gaearon/pen/rrpgNB?editors=1010)**
Натисніть на посилання вище, щоб відкрити онлайн-редактор. Спробуйте відредагувати код і подивіться, як зміниться результат. Більшість сторінок цього посібника матимуть такі інтерактивні приклади.
diff --git a/content/docs/higher-order-components.md b/content/docs/higher-order-components.md
index d7eb75d83..2caecfac0 100644
--- a/content/docs/higher-order-components.md
+++ b/content/docs/higher-order-components.md
@@ -4,6 +4,14 @@ title: Компоненти вищого порядку
permalink: docs/higher-order-components.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> Higher-order components are not commonly used in modern React code.
+
+
+
Компонент вищого порядку (КВП) — це просунута технологія для повторного використання логіки компоненту. Сам по собі КВП не є частиною React API, але через композиційну природу компонентів він є розповсюдженним патерном проектування.
Тобто, **компонент вищого порядку — це функція, яка приймає компонент та повертає новий компонент.**
@@ -14,7 +22,7 @@ const EnhancedComponent = higherOrderComponent(WrappedComponent);
Якщо звичайний компонент трансформує пропси у UI, то компонент вищого порядку трансформує один компонент у інший.
-КВП поширені у таких сторонніх бібліотеках, як [`connect`](https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#connect) у Redux, або [`createFragmentContainer`](http://facebook.github.io/relay/docs/en/fragment-container.html) у Relay.
+КВП поширені у таких сторонніх бібліотеках, як [`connect`](https://react-redux.js.org/api/connect) у Redux, або [`createFragmentContainer`](https://relay.dev/docs/v10.1.3/fragment-container/#createfragmentcontainer) у Relay.
У цьому розділі ми обговоримо чому компоненти вищого порядку корисні та як створювати їх власноруч.
@@ -297,7 +305,7 @@ const EnhancedComponent = enhance(WrappedComponent)
## Конвенція: повертайте ім’я обгорнутого компонента для легшого дебагу {#convention-wrap-the-display-name-for-easy-debugging}
-Створений КВП компонент-контейнер відображається у [React Developer Tools](https://github.com/facebook/react-devtools), як і будь-який інший компонент. Для того, щоб полегшити процес налагодження, визначте відображуване ім’я, яке повідомляє, що це результат КВП.
+Створений КВП компонент-контейнер відображається у [React Developer Tools](https://github.com/facebook/react/tree/main/packages/react-devtools), як і будь-який інший компонент. Для того, щоб полегшити процес налагодження, визначте відображуване ім’я, яке повідомляє, що це результат КВП.
Найпоширеніший прийом - обгортати відображуване ім’я загорнутого компонента. Отже, якщо ваш компонент вищого порядку названий `withSubscription`, а відображене ім’я загорнутого компонента - `CommentList`, визначте відображуване ім'я як `WithSubscription(CommentList)`:
diff --git a/content/docs/hooks-custom.md b/content/docs/hooks-custom.md
index c28843396..72c6dfe5d 100644
--- a/content/docs/hooks-custom.md
+++ b/content/docs/hooks-custom.md
@@ -6,6 +6,16 @@ next: hooks-reference.html
prev: hooks-rules.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Reusing Logic with Custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks)
+
+
+
*Хуки* — це новинка в React 16.8. Вони дозволяють вам використовувати стан та інші можливості React без написання класу.
Створення власних хуків дозволить вам винести логіку компонента у функції, придатні для повторного використання.
diff --git a/content/docs/hooks-effect.md b/content/docs/hooks-effect.md
index f7220094f..23f640b31 100644
--- a/content/docs/hooks-effect.md
+++ b/content/docs/hooks-effect.md
@@ -6,6 +6,18 @@ next: hooks-rules.html
prev: hooks-state.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Synchronizing with Effects](https://react.dev/learn/synchronizing-with-effects)
+> - [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
+> - [`useEffect`](https://react.dev/reference/react/useEffect)
+
+
+
*Хуки* — це новинка в React 16.8. Вони дозволяють вам використовувати стан та інші можливості React без написання класу.
*Хук ефекту* дозволяє вам виконувати побічні ефекти в функціональному компоненті:
diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md
index 9a4e591c1..a8473c5e6 100644
--- a/content/docs/hooks-faq.md
+++ b/content/docs/hooks-faq.md
@@ -5,6 +5,14 @@ permalink: docs/hooks-faq.html
prev: hooks-reference.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> The new documentation pages teaches React with Hooks.
+
+
+
*Хуки* — це новинка в React 16.8. Вони дозволяють вам використовувати стан та інші можливості React без написання класу.
На цій сторінці ви знайдете відповіді на деякі поширені питання щодо [хуків](/docs/hooks-overview.html).
@@ -97,8 +105,6 @@ prev: hooks-reference.html
Нашою метою є покриття всіх можливостей класів хуками якнайшвидше. Наразі немає альтернативи у вигляді хуків для таких рідковживаних методів життєвого циклу як `getSnapshotBeforeUpdate`, `getDerivedStateFromError` та `componentDidCatch`, але ми плануємо скоро їх додати.
-Оскільки хуки з'явились зовсім нещодавно, то не всі сторонні бібліотеки можуть бути сумісними з ними.
-
### Чи замінять хуки рендер пропси та компоненти вищого порядку? {#do-hooks-replace-render-props-and-higher-order-components}
Часто рендер пропси та компоненти вищого порядку рендерять лише одного нащадка. Ми вважаємо, що хуки є простішим шляхом для того, щоб зробити це. Все ще ми можемо використовувати обидва шаблони (наприклад, віртуальний компонент скролінгу може мати проп `renderItem` чи візуальний контейнер може мати власну структуру DOM). Але у більшості випадків, хуків буде достатньо для зменшення кількості вкладень у ващому дереві.
@@ -150,7 +156,7 @@ function Example() {
```js{3,20-22,29-31}
import React from 'react';
-import ReactDOM from 'react-dom';
+import ReactDOM from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import Counter from './Counter';
@@ -169,7 +175,7 @@ afterEach(() => {
it('can render and update a counter', () => {
// Тестуємо перший рендер і ефект
act(() => {
- ReactDOM.render(, container);
+ ReactDOM.createRoot(container).render();
});
const button = container.querySelector('button');
const label = container.querySelector('p');
@@ -335,9 +341,7 @@ function useWindowPosition() {
Наразі ви можете зробити це вручну, [використавши реф](#is-there-something-like-instance-variables):
-```js{6,8}
-function Counter() {
- const [count, setCount] = useState(0);
+Sometimes, you need previous props to **clean up an effect.** For example, you might have an effect that subscribes to a socket based on the `userId` prop. If the `userId` prop changes, you want to unsubscribe from the _previous_ `userId` and subscribe to the _next_ one. You don't need to do anything special for this to work:
const prevCountRef = useRef();
useEffect(() => {
@@ -914,8 +918,6 @@ function DeepChild(props) {
>Примітка
>
>Ми радимо [передавати `dispatch` у контексті вниз](#how-to-avoid-passing-callbacks-down), а не окремих функцій зворотнього виклику в пропсах. Підхід нижче описаний лише для повноти і у якості запасного виходу.
->
->Також зверніть увагу, що цей шаблон може спричинити проблеми у [конкурентному режимі](/blog/2018/03/27/update-on-async-rendering.html). Ми плануємо надати більш зручні альтернативи у майбутньому, але найбезпечнішим рішенням наразі — скасування функції зворотнього виклику при зміні хоча б одного значення від якого він залежить.
У нечастих випадках вам може бути потрібно запам'ятати функцію зворотнього виклику, використавши [`useCallback`](/docs/hooks-reference.html#usecallback), але запам'ятовування не спрацює як слід, тому що внутрішня функція повинна повторно створюватись надто часто. Якщо функція, яку ви запам'ятовуєте, є оброником події і не використовується під час рендерингу, то ви можете [використати реф як змінну екземпляра](#is-there-something-like-instance-variables) і зберегти у ньому останнє значення вручну:
diff --git a/content/docs/hooks-intro.md b/content/docs/hooks-intro.md
index 89e4c822f..ff222e217 100644
--- a/content/docs/hooks-intro.md
+++ b/content/docs/hooks-intro.md
@@ -5,6 +5,18 @@ permalink: docs/hooks-intro.html
next: hooks-overview.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach React with Hooks:
+>
+> - [Quick Start](https://react.dev/learn)
+> - [Tutorial](https://react.dev/learn/tutorial-tic-tac-toe)
+> - [`react`: Hooks](https://react.dev/reference/react)
+
+
+
*Хуки* — це новинка в React 16.8. Вони дозволяють вам використовувати стан та інші можливості React без написання класу.
```js{4,5}
@@ -96,7 +108,7 @@ React не має можливості "прикріпити" до компон
Нам відомо, що розробники React фокусуються на виконанні цілей і не завжди щоразу мають час на перегляд випущеного нового API. Хуки - абсолютно новий концепт, а тому може бути краще почекати виходу більшої кількості прикладів та посібників перед прийняттям рішення про їхнє вивчення чи використання.
-Ми також розуміємо, що поріг додавання нових концепцій у React є досить високим. Тому для зацікавлених ми підготували [детальний запит про обговорення](https://github.com/reactjs/rfcs/pull/68), в якому знайдете більше деталей та пояснення нашої мотивації, а також додаткову інформацію щодо технічних аспектів та основи дизайну хуків.
+We also understand that the bar for adding a new primitive to React is extremely high. For curious readers, we have prepared a [detailed RFC](https://github.com/reactjs/rfcs/pull/68) that dives into motivation with more details, and provides extra perspective on the specific design decisions and related prior art.
**Важливим є те, що хуки працюють разом із існуючим кодом, тому їх можна впроваджувати поступово.** Немає необхідності прямо зараз мігрувати на хуки. Ми рекомендуємо уникати великого переписання коду, особливо для існуючих складних класових компонентів. Необхідно докласти трішки зусиль, щоб почати "думати хуками". Ми виявили, що найкраще спочатку почати використовувати хуки в нових і не критичних компонентах, а також впевнитися, що всі в команді комфортно їх можуть використовувати. Після того, як ви спробуєте хуки, не соромтеся [надсилати нам](https://github.com/facebook/react/issues/new) відгуки, неважливо хороші чи погані.
diff --git a/content/docs/hooks-overview.md b/content/docs/hooks-overview.md
index 5b4c037b0..fd1b7e847 100644
--- a/content/docs/hooks-overview.md
+++ b/content/docs/hooks-overview.md
@@ -6,6 +6,18 @@ next: hooks-state.html
prev: hooks-intro.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach React with Hooks:
+>
+> - [Quick Start](https://react.dev/learn)
+> - [Tutorial](https://react.dev/learn/tutorial-tic-tac-toe)
+> - [`react`: Hooks](https://react.dev/reference/react)
+
+
+
*Хуки* -- новинка у React 16.8, яка дозволяє використовувати стан та інші можливості React без написання класу.
Хуки [зворотньо сумісні](/docs/hooks-intro.html#no-breaking-changes). Майте на увазі, що це біглий огляд хуків, який більше підійде для досвідчених користувачів React. Якщо ви заплутаєтесь, шукайте такий жовтий блок:
diff --git a/content/docs/hooks-reference.md b/content/docs/hooks-reference.md
index 4805d0e32..77400d107 100644
--- a/content/docs/hooks-reference.md
+++ b/content/docs/hooks-reference.md
@@ -6,6 +6,16 @@ prev: hooks-custom.html
next: hooks-faq.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React:
+>
+> - [`react`: Hooks](https://react.dev/reference/react)
+
+
+
*Хуки* — це новинка в React 16.8. Вони дозволяють вам використовувати стан та інші можливості React без написання класу.
Ця сторінка описує API для вбудованих у React хуків.
@@ -24,11 +34,25 @@ next: hooks-faq.html
- [`useImperativeHandle`](#useimperativehandle)
- [`useLayoutEffect`](#uselayouteffect)
- [`useDebugValue`](#usedebugvalue)
+ - [`useDeferredValue`](#usedeferredvalue)
+ - [`useTransition`](#usetransition)
+ - [`useId`](#useid)
+- [Library Hooks](#library-hooks)
+ - [`useSyncExternalStore`](#usesyncexternalstore)
+ - [`useInsertionEffect`](#useinsertioneffect)
## Базові хуки {#basic-hooks}
### `useState` {#usestate}
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useState`](https://react.dev/reference/react/useState).
+
+
+
```js
const [state, setState] = useState(initialState);
```
@@ -76,6 +100,7 @@ function Counter({initialCount}) {
> На відміну від методу `setState` у класових компонентах, `useState` не об'єднує оновлювані об'єкти автоматично. Ви можете відтворити таку поведінку, комбінуючи функціональну форму оновлення і синтаксис розширення об'єктів:
>
> ```js
+> const [state, setState] = useState({});
> setState(prevState => {
> // Object.assign також спрацює
> return {...prevState, ...updatedValues};
@@ -101,8 +126,24 @@ const [state, setState] = useState(() => {
Зверніть увагу, що React-у може знадобитись відрендерити конкретний компонент перед припиненням оновлення. Це не повинно викликати занепокоєння, тому що React необов'язково опуститься "глибше" в дерево. Якщо ви здійснюєте вартісні обчислення під час рендерингу, ви можете оптимізувати їх, використавши `useMemo`.
+#### Batching of state updates {#batching-of-state-updates}
+
+React may group several state updates into a single re-render to improve performance. Normally, this improves performance and shouldn't affect your application's behavior.
+
+Before React 18, only updates inside React event handlers were batched. Starting with React 18, [batching is enabled for all updates by default](/blog/2022/03/08/react-18-upgrade-guide.html#automatic-batching). Note that React makes sure that updates from several *different* user-initiated events -- for example, clicking a button twice -- are always processed separately and do not get batched. This prevents logical mistakes.
+
+In the rare case that you need to force the DOM update to be applied synchronously, you may wrap it in [`flushSync`](/docs/react-dom.html#flushsync). However, this can hurt performance so do this only where needed.
+
### `useEffect` {#useeffect}
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useEffect`](https://react.dev/reference/react/useEffect).
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useImperativeHandle`](https://react.dev/reference/react/useImperativeHandle).
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useLayoutEffect`](https://react.dev/reference/react/useLayoutEffect).
+
+
+
+
Сигнатура хука є ідентичною `useEffect`, але він запускається синхронно після всіх змін DOM. Використовуйте це для читання розмітки з DOM і синхронних повторних рендерів. Оновлення, заплановані всередині `useLayoutEffect`, будуть виконані синхронно перед тим, як браузер відобразить їх.
Віддайте перевагу використанню `useEffect`, коли це можливо, щоб уникнути блокування візуальних оновлень.
@@ -470,6 +573,15 @@ FancyInput = forwardRef(FancyInput);
### `useDebugValue` {#usedebugvalue}
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useDebugValue`](https://react.dev/reference/react/useDebugValue).
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue).
+
+
+
+
+```js
+const deferredValue = useDeferredValue(value);
+```
+
+`useDeferredValue` accepts a value and returns a new copy of the value that will defer to more urgent updates. If the current render is the result of an urgent update, like user input, React will return the previous value and then render the new value after the urgent render has completed.
+
+This hook is similar to user-space hooks which use debouncing or throttling to defer updates. The benefits to using `useDeferredValue` is that React will work on the update as soon as other work finishes (instead of waiting for an arbitrary amount of time), and like [`startTransition`](/docs/react-api.html#starttransition), deferred values can suspend without triggering an unexpected fallback for existing content.
+
+#### Memoizing deferred children {#memoizing-deferred-children}
+`useDeferredValue` only defers the value that you pass to it. If you want to prevent a child component from re-rendering during an urgent update, you must also memoize that component with [`React.memo`](/docs/react-api.html#reactmemo) or [`React.useMemo`](/docs/hooks-reference.html#usememo):
+
+```js
+function Typeahead() {
+ const query = useSearchQuery('');
+ const deferredQuery = useDeferredValue(query);
+
+ // Memoizing tells React to only re-render when deferredQuery changes,
+ // not when query changes.
+ const suggestions = useMemo(() =>
+ ,
+ [deferredQuery]
+ );
+
+ return (
+ <>
+
+
+ {suggestions}
+
+ >
+ );
+}
+```
+
+Memoizing the children tells React that it only needs to re-render them when `deferredQuery` changes and not when `query` changes. This caveat is not unique to `useDeferredValue`, and it's the same pattern you would use with similar hooks that use debouncing or throttling.
+
+### `useTransition` {#usetransition}
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useTransition`](https://react.dev/reference/react/useTransition).
+
+
+
+
+```js
+const [isPending, startTransition] = useTransition();
+```
+
+Returns a stateful value for the pending state of the transition, and a function to start it.
+
+`startTransition` lets you mark updates in the provided callback as transitions:
+
+```js
+startTransition(() => {
+ setCount(count + 1);
+});
+```
+
+`isPending` indicates when a transition is active to show a pending state:
+
+```js
+function App() {
+ const [isPending, startTransition] = useTransition();
+ const [count, setCount] = useState(0);
+
+ function handleClick() {
+ startTransition(() => {
+ setCount(c => c + 1);
+ });
+ }
+
+ return (
+
+ {isPending && }
+ {count}
+
+ );
+}
+```
+
+> Note:
+>
+> Updates in a transition yield to more urgent updates such as clicks.
+>
+> Updates in a transition will not show a fallback for re-suspended content. This allows the user to continue interacting with the current content while rendering the update.
+
+### `useId` {#useid}
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useId`](https://react.dev/reference/react/useId).
+
+
+
+
+```js
+const id = useId();
+```
+
+`useId` is a hook for generating unique IDs that are stable across the server and client, while avoiding hydration mismatches.
+
+> Note
+>
+> `useId` is **not** for generating [keys in a list](/docs/lists-and-keys.html#keys). Keys should be generated from your data.
+
+For a basic example, pass the `id` directly to the elements that need it:
+
+```js
+function Checkbox() {
+ const id = useId();
+ return (
+ <>
+
+
+ >
+ );
+};
+```
+
+For multiple IDs in the same component, append a suffix using the same `id`:
+
+```js
+function NameFields() {
+ const id = useId();
+ return (
+
+
+
+
+
+
+
+
+
+
+ );
+}
+```
+
+> Note:
+>
+> `useId` generates a string that includes the `:` token. This helps ensure that the token is unique, but is not supported in CSS selectors or APIs like `querySelectorAll`.
+>
+> `useId` supports an `identifierPrefix` to prevent collisions in multi-root apps. To configure, see the options for [`hydrateRoot`](/docs/react-dom-client.html#hydrateroot) and [`ReactDOMServer`](/docs/react-dom-server.html).
+
+## Library Hooks {#library-hooks}
+
+The following Hooks are provided for library authors to integrate libraries deeply into the React model, and are not typically used in application code.
+
+### `useSyncExternalStore` {#usesyncexternalstore}
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore).
+
+
+
+
+```js
+const state = useSyncExternalStore(subscribe, getSnapshot[, getServerSnapshot]);
+```
+
+`useSyncExternalStore` is a hook recommended for reading and subscribing from external data sources in a way that's compatible with concurrent rendering features like selective hydration and time slicing.
+
+This method returns the value of the store and accepts three arguments:
+- `subscribe`: function to register a callback that is called whenever the store changes.
+- `getSnapshot`: function that returns the current value of the store.
+- `getServerSnapshot`: function that returns the snapshot used during server rendering.
+
+The most basic example simply subscribes to the entire store:
+
+```js
+const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
+```
+
+However, you can also subscribe to a specific field:
+
+```js
+const selectedField = useSyncExternalStore(
+ store.subscribe,
+ () => store.getSnapshot().selectedField,
+);
+```
+
+When server rendering, you must serialize the store value used on the server, and provide it to `useSyncExternalStore`. React will use this snapshot during hydration to prevent server mismatches:
+
+```js
+const selectedField = useSyncExternalStore(
+ store.subscribe,
+ () => store.getSnapshot().selectedField,
+ () => INITIAL_SERVER_SNAPSHOT.selectedField,
+);
+```
+
+> Note:
+>
+> `getSnapshot` must return a cached value. If getSnapshot is called multiple times in a row, it must return the same exact value unless there was a store update in between.
+>
+> A shim is provided for supporting multiple React versions published as `use-sync-external-store/shim`. This shim will prefer `useSyncExternalStore` when available, and fallback to a user-space implementation when it's not.
+>
+> As a convenience, we also provide a version of the API with automatic support for memoizing the result of getSnapshot published as `use-sync-external-store/with-selector`.
+
+### `useInsertionEffect` {#useinsertioneffect}
+
+
+
+> This content is out of date.
+>
+> Read the new React documentation for [`useInsertionEffect`](https://react.dev/reference/react/useInsertionEffect).
+
+
+
+```js
+useInsertionEffect(didUpdate);
+```
+
+The signature is identical to `useEffect`, but it fires synchronously _before_ all DOM mutations. Use this to inject styles into the DOM before reading layout in [`useLayoutEffect`](#uselayouteffect). Since this hook is limited in scope, this hook does not have access to refs and cannot schedule updates.
+
+> Note:
+>
+> `useInsertionEffect` should be limited to css-in-js library authors. Prefer [`useEffect`](#useeffect) or [`useLayoutEffect`](#uselayouteffect) instead.
diff --git a/content/docs/hooks-state.md b/content/docs/hooks-state.md
index 821d9876a..882d64d09 100644
--- a/content/docs/hooks-state.md
+++ b/content/docs/hooks-state.md
@@ -6,6 +6,17 @@ next: hooks-effect.html
prev: hooks-overview.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [State: A Component's Memory](https://react.dev/learn/state-a-components-memory)
+> - [`useState`](https://react.dev/reference/react/useState)
+
+
+
*Хуки* — це новинка в React 16.8. Вони дозволяють вам використовувати стан та інші можливості React без написання класу.
На [початковій сторінці](/docs/hooks-intro.html) ми ознайомились з хуками на цьому прикладі:
diff --git a/content/docs/how-to-contribute.md b/content/docs/how-to-contribute.md
index d8160a313..86fdb0c87 100644
--- a/content/docs/how-to-contribute.md
+++ b/content/docs/how-to-contribute.md
@@ -11,9 +11,9 @@ redirect_from:
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and answers some questions that you may have.
-### [Code of Conduct](https://github.com/facebook/react/blob/master/CODE_OF_CONDUCT.md) {#code-of-conduct}
+### [Code of Conduct](https://github.com/facebook/react/blob/main/CODE_OF_CONDUCT.md) {#code-of-conduct}
-Facebook has adopted the [Contributor Covenant](https://www.contributor-covenant.org/) as its Code of Conduct, and we expect project participants to adhere to it. Please read [the full text](https://github.com/facebook/react/blob/master/CODE_OF_CONDUCT.md) so that you can understand what actions will and will not be tolerated.
+Facebook has adopted the [Contributor Covenant](https://www.contributor-covenant.org/) as its Code of Conduct, and we expect project participants to adhere to it. Please read [the full text](https://github.com/facebook/react/blob/main/CODE_OF_CONDUCT.md) so that you can understand what actions will and will not be tolerated.
### Open Development {#open-development}
@@ -23,19 +23,19 @@ All work on React happens directly on [GitHub](https://github.com/facebook/react
React follows [semantic versioning](https://semver.org/). We release patch versions for critical bugfixes, minor versions for new features or non-essential changes, and major versions for any breaking changes. When we make breaking changes, we also introduce deprecation warnings in a minor version so that our users learn about the upcoming changes and migrate their code in advance. Learn more about our commitment to stability and incremental migration in [our versioning policy](/docs/faq-versioning.html).
-Every significant change is documented in the [changelog file](https://github.com/facebook/react/blob/master/CHANGELOG.md).
+Every significant change is documented in the [changelog file](https://github.com/facebook/react/blob/main/CHANGELOG.md).
### Branch Organization {#branch-organization}
-Submit all changes directly to the [`master branch`](https://github.com/facebook/react/tree/master). We don't use separate branches for development or for upcoming releases. We do our best to keep `master` in good shape, with all tests passing.
+Submit all changes directly to the [`main branch`](https://github.com/facebook/react/tree/main). We don't use separate branches for development or for upcoming releases. We do our best to keep `main` in good shape, with all tests passing.
-Code that lands in `master` must be compatible with the latest stable release. It may contain additional features, but no breaking changes. We should be able to release a new minor version from the tip of `master` at any time.
+Code that lands in `main` must be compatible with the latest stable release. It may contain additional features, but no breaking changes. We should be able to release a new minor version from the tip of `main` at any time.
### Feature Flags {#feature-flags}
-To keep the `master` branch in a releasable state, breaking changes and experimental features must be gated behind a feature flag.
+To keep the `main` branch in a releasable state, breaking changes and experimental features must be gated behind a feature flag.
-Feature flags are defined in [`packages/shared/ReactFeatureFlags.js`](https://github.com/facebook/react/blob/master/packages/shared/ReactFeatureFlags.js). Some builds of React may enable different sets of feature flags; for example, the React Native build may be configured differently than React DOM. These flags are found in [`packages/shared/forks`](https://github.com/facebook/react/tree/master/packages/shared/forks). Feature flags are statically typed by Flow, so you can run `yarn flow` to confirm that you've updated all the necessary files.
+Feature flags are defined in [`packages/shared/ReactFeatureFlags.js`](https://github.com/facebook/react/blob/main/packages/shared/ReactFeatureFlags.js). Some builds of React may enable different sets of feature flags; for example, the React Native build may be configured differently than React DOM. These flags are found in [`packages/shared/forks`](https://github.com/facebook/react/tree/main/packages/shared/forks). Feature flags are statically typed by Flow, so you can run `yarn flow` to confirm that you've updated all the necessary files.
React's build system will strip out disabled feature branches before publishing. A continuous integration job runs on every commit to check for changes in bundle size. You can use the change in size as a signal that a feature was gated correctly.
@@ -70,7 +70,7 @@ If you're only fixing a bug, it's fine to submit a pull request right away but w
Working on your first Pull Request? You can learn how from this free video series:
-**[How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)**
+**[How to Contribute to an Open Source Project on GitHub](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)**
To help you get your feet wet and get you familiar with our contribution process, we have a list of **[good first issues](https://github.com/facebook/react/issues?q=is:open+is:issue+label:"good+first+issue")** that contain bugs that have a relatively limited scope. This is a great place to get started.
@@ -84,12 +84,12 @@ The core team is monitoring for pull requests. We will review your pull request
**Before submitting a pull request,** please make sure the following is done:
-1. Fork [the repository](https://github.com/facebook/react) and create your branch from `master`.
+1. Fork [the repository](https://github.com/facebook/react) and create your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch TestName` is helpful in development.
-5. Run `yarn test-prod` to test in the production environment. It supports the same options as `yarn test`.
-6. If you need a debugger, run `yarn debug-test --watch TestName`, open `chrome://inspect`, and press "Inspect".
+5. Run `yarn test --prod` to test in the production environment.
+6. If you need a debugger, run `yarn test --debug --watch TestName`, open `chrome://inspect`, and press "Inspect".
7. Format your code with [prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only check changed files.
9. Run the [Flow](https://flowtype.org/) typechecks (`yarn flow`).
@@ -103,7 +103,7 @@ In order to accept your pull request, we need you to submit a CLA. You only need
### Contribution Prerequisites {#contribution-prerequisites}
-* You have [Node](https://nodejs.org) installed at v8.0.0+ and [Yarn](https://yarnpkg.com/en/) at v1.2.0+.
+* You have [Node](https://nodejs.org) installed at LTS and [Yarn](https://yarnpkg.com/en/) at v1.2.0+.
* You have [JDK](https://www.oracle.com/technetwork/java/javase/downloads/index.html) installed.
* You have `gcc` installed or are comfortable installing a compiler if needed. Some of our dependencies may require a compilation step. On OS X, the Xcode Command Line Tools will cover this. On Ubuntu, `apt-get install build-essential` will install the required packages. Similar commands should work on other Linux distros. Windows will require some additional steps, see the [`node-gyp` installation instructions](https://github.com/nodejs/node-gyp#installation) for details.
* You are familiar with Git.
@@ -117,26 +117,26 @@ Then, you can run several commands:
* `yarn linc` is like `yarn lint` but faster because it only checks files that differ in your branch.
* `yarn test` runs the complete test suite.
* `yarn test --watch` runs an interactive test watcher.
+* `yarn test --prod` runs tests in the production environment.
* `yarn test ` runs tests with matching filenames.
-* `yarn test-prod` runs tests in the production environment. It supports all the same options as `yarn test`.
* `yarn debug-test` is just like `yarn test` but with a debugger. Open `chrome://inspect` and press "Inspect".
* `yarn flow` runs the [Flow](https://flowtype.org/) typechecks.
* `yarn build` creates a `build` folder with all the packages.
* `yarn build react/index,react-dom/index --type=UMD` creates UMD builds of just React and ReactDOM.
-We recommend running `yarn test` (or its variations above) to make sure you don't introduce any regressions as you work on your change. However it can be handy to try your build of React in a real project.
+We recommend running `yarn test` (or its variations above) to make sure you don't introduce any regressions as you work on your change. However, it can be handy to try your build of React in a real project.
First, run `yarn build`. This will produce pre-built bundles in `build` folder, as well as prepare npm packages inside `build/packages`.
The easiest way to try your changes is to run `yarn build react/index,react-dom/index --type=UMD` and then open `fixtures/packaging/babel-standalone/dev.html`. This file already uses `react.development.js` from the `build` folder so it will pick up your changes.
-If you want to try your changes in your existing React project, you may copy `build/dist/react.development.js`, `build/dist/react-dom.development.js`, or any other build products into your app and use them instead of the stable version.
+If you want to try your changes in your existing React project, you may copy `build/node_modules/react/umd/react.development.js`, `build/node_modules/react-dom/umd/react-dom.development.js`, or any other build products into your app and use them instead of the stable version.
If your project uses React from npm, you may delete `react` and `react-dom` in its dependencies and use `yarn link` to point them to your local `build` folder. Note that **instead of `--type=UMD` you'll want to pass `--type=NODE` when building**. You'll also need to build the `scheduler` package:
```sh
cd ~/path_to_your_react_clone/
-yarn build react/index,react-dom/index,scheduler --type=NODE
+yarn build react/index,react/jsx,react-dom/index,scheduler --type=NODE
cd build/node_modules/react
yarn link
diff --git a/content/docs/implementation-notes.md b/content/docs/implementation-notes.md
index b345f7d5d..ff67f062f 100644
--- a/content/docs/implementation-notes.md
+++ b/content/docs/implementation-notes.md
@@ -32,10 +32,11 @@ The reconciler itself doesn't have a public API. [Renderers](/docs/codebase-over
Let's consider the first time you mount a component:
```js
-ReactDOM.render(, rootEl);
+const root = ReactDOM.createRoot(rootEl);
+root.render();
```
-React DOM will pass `` along to the reconciler. Remember that `` is a React element, that is, a description of *what* to render. You can think about it as a plain object:
+`root.render` will pass `` along to the reconciler. Remember that `` is a React element, that is, a description of *what* to render. You can think about it as a plain object:
```js
console.log();
@@ -236,9 +237,9 @@ This is working but still far from how the reconciler is really implemented. The
The key feature of React is that you can re-render everything, and it won't recreate the DOM or reset the state:
```js
-ReactDOM.render(, rootEl);
+root.render();
// Should reuse the existing DOM:
-ReactDOM.render(, rootEl);
+root.render();
```
However, our implementation above only knows how to mount the initial tree. It can't perform updates on it because it doesn't store all the necessary information, such as all the `publicInstance`s, or which DOM `node`s correspond to which components.
@@ -412,7 +413,7 @@ If you're struggling to imagine how an internal instance tree is structured in m
-To complete this refactoring, we will introduce a function that mounts a complete tree into a container node, just like `ReactDOM.render()`. It returns a public instance, also like `ReactDOM.render()`:
+To complete this refactoring, we will introduce a function that mounts a complete tree into a container node and a public instance:
```js
function mountTree(element, containerNode) {
diff --git a/content/docs/integrating-with-other-libraries.md b/content/docs/integrating-with-other-libraries.md
index f90ee312a..6a07a9c3b 100644
--- a/content/docs/integrating-with-other-libraries.md
+++ b/content/docs/integrating-with-other-libraries.md
@@ -4,6 +4,19 @@ title: Взаємодія зі сторонніми бібліотеками
permalink: docs/integrating-with-other-libraries.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React:
+>
+> - [`useSyncExternalStore`: Subscribing to an external store
+](https://react.dev/reference/react/useSyncExternalStore#subscribing-to-an-external-store)
+> - [`createPortal`: Rendering React components into non-React DOM nodes
+](https://react.dev/reference/react-dom/createPortal#rendering-react-components-into-non-react-dom-nodes)
+
+
+
React можна використовувати у будь-якому веб-додатку. Його можна вбудовувати в інші додатки, та, з невеликими зусиллями, інші додатки можна вбудувати в React. У цьому гайді ми розглянемо деякі з більш поширених випадків використання React, а саме - інтеграцію з [jQuery](https://jquery.com/) та [Backbone](https://backbonejs.org/). Проте ці ж ідеї можна застосувати до інтеграції компонентів з будь-яким іншим кодом.
## Інтеграція з плагінами, які змінюють DOM {#integrating-with-dom-manipulation-plugins}
@@ -190,9 +203,9 @@ class Chosen extends React.Component {
## Інтеграція з іншими візуальними бібліотеками {#integrating-with-other-view-libraries}
-React можна вбудовувати в інші додатки, завдяки гнучкості функції [`ReactDOM.render()`](/docs/react-dom.html#render).
+React можна вбудовувати в інші додатки, завдяки гнучкості функції [`createRoot()`](/docs/react-dom-client.html#createRoot).
-Хоча React широко використовується для завантаження єдиного кореневого компоненту в DOM, метод `ReactDOM.render()` також може бути викликаний багато разів для незалежних частин UI, що можуть бути такими малими, як кнопка, або такими великими, як окремий додаток.
+Хоча React широко використовується для завантаження єдиного кореневого компоненту в DOM, метод `createRoot()` також може бути викликаний багато разів для незалежних частин UI, що можуть бути такими малими, як кнопка, або такими великими, як окремий додаток.
Насправді, саме так Facebook використовує React. Такий підхід дозволяє писати програми частинами і комбінувати їх з шаблонами, створеними на сервері, або з іншим клієнтським кодом.
@@ -216,15 +229,9 @@ function Button() {
return Say Hello;
}
-ReactDOM.render(
- ,
- document.getElementById('container'),
- function() {
- $('#btn').click(function() {
- alert('Hello!');
- });
- }
-);
+$('#btn').click(function() {
+ alert('Hello!');
+});
```
З цього моменту можете починати передавати все більше логіки самому компоненту й застосовувати все більше й більше React-підходів до написання коду. Наприклад, у компонентах найкраще не покладатись на ідентифікатори тому, що один і той самий компонент може бути відрендерений декілька разів. Натомість, використовуємо [систему подій React](/docs/handling-events.html) та реєструємо метод-обробник події click безпосередньо на React-елементі ``:
@@ -240,36 +247,34 @@ function HelloButton() {
}
return ;
}
-
-ReactDOM.render(
- ,
- document.getElementById('container')
-);
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/RVKbvW?editors=1010)
-Ви можете написати скільки завгодно ізольованих компонентів, а також ренедрити їх у різних DOM-контейнерах за допомогою функції`ReactDOM.render()`. Поступово, коли трансформуєте все більше коду програми у React-компоненти, можна буде об’єднати їх в більші компоненти, а деякі з викликів до `ReactDOM.render()` — перемістити вгору за ієрархією.
+Ви можете написати скільки завгодно ізольованих компонентів, а також ренедрити їх у різних DOM-контейнерах за допомогою функції`ReactDOM.createRoot()`. Поступово, коли трансформуєте все більше коду програми у React-компоненти, можна буде об’єднати їх в більші компоненти, а деякі з викликів до `ReactDOM.createRoot()` — перемістити вгору за ієрархією.
### Вставка React у представлення Backbone {#embedding-react-in-a-backbone-view}
Представлення у [Backbone](https://backbonejs.org/) зазвичай використовують HTML-рядки або функції, які генерують рядкові шаблони, для створення вмісту їх DOM-елементів. Цей процес також може бути замінений за допомого рендеру React-компонентів.
-Нижче – приклад того, як ми створюємо Backbone-представлення, що називається `ParagraphView`. Воно перевизначить `render()` метод Backbone для рендерингу React-компоненту `` у DOM-елемент, наданий Backbone (`this.el`). Тут ми також використовуємо метод [`ReactDOM.render()`](/docs/react-dom.html#render):
+Нижче – приклад того, як ми створюємо Backbone-представлення, що називається `ParagraphView`. Воно перевизначить `render()` метод Backbone для рендерингу React-компоненту `` у DOM-елемент, наданий Backbone (`this.el`). Тут ми також використовуємо метод [`ReactDOM.createRoot()`](/docs/react-dom-client.html#createroot):
-```js{1,5,8,12}
+```js{7,11,15}
function Paragraph(props) {
return
{props.text}
;
}
const ParagraphView = Backbone.View.extend({
+ initialize(options) {
+ this.reactRoot = ReactDOM.createRoot(this.el);
+ },
render() {
const text = this.model.get('text');
- ReactDOM.render(, this.el);
+ this.reactRoot.render();
return this;
},
remove() {
- ReactDOM.unmountComponentAtNode(this.el);
+ this.reactRoot.unmount();
Backbone.View.prototype.remove.call(this);
}
});
@@ -277,7 +282,7 @@ const ParagraphView = Backbone.View.extend({
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/gWgOYL?editors=0010)
-Важливо також викликати метод `ReactDOM.unmountComponentAtNode()` у середині методу `remove`, щоб React видаляв зареєстровані обробники подій та інші ресурси, які пов’язані з деревом компонентів, у момент, коли воно видаляється.
+Важливо також викликати метод `root.unmount()` у середині методу `remove`, щоб React видаляв зареєстровані обробники подій та інші ресурси, які пов’язані з деревом компонентів, у момент, коли воно видаляється.
Коли компонент видаляється з React-дерева *зсередини*, очищення проводиться автоматично. Проте оскільки ми видаляємо все дерево вручну, мусимо викликати цей метод.
@@ -428,10 +433,8 @@ function Example(props) {
}
const model = new Backbone.Model({ firstName: 'Frodo' });
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render();
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/PmWwwa?editors=0010)
diff --git a/content/docs/introducing-jsx.md b/content/docs/introducing-jsx.md
index c71df3b25..4aa4b4fd5 100644
--- a/content/docs/introducing-jsx.md
+++ b/content/docs/introducing-jsx.md
@@ -6,6 +6,18 @@ prev: hello-world.html
next: rendering-elements.html
---
+
+
+>
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Writing Markup with JSX](https://react.dev/learn/writing-markup-with-jsx)
+> - [JavaScript in JSX with Curly Braces](https://react.dev/learn/javascript-in-jsx-with-curly-braces)
+
+
;
-
-ReactDOM.render(
- element,
- document.getElementById('root')
-);
```
ви можете помістити будь-який валідний [JavaScript вираз](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) всередину фігурних дужок у JSX. Наприклад, `2 + 2`, `user.firstName`, або `formatName(user)` є валідними виразами JavaScript.
@@ -61,14 +68,9 @@ const element = (
Hello, {formatName(user)}!
);
-
-ReactDOM.render(
- element,
- document.getElementById('root')
-);
```
-[Спробуйте на CodePen](codepen://introducing-jsx)
+[Спробуйте на CodePen](https://codepen.io/gaearon/pen/PGEjdG?editors=1010)
Ми розбиваємо JSX на декілька рядків для покращення читабельності. Хоча це не потрібно, ми також рекомендуємо охоплювати його дужками, щоб уникнути проблем, пов'язаних з [автоматичною вставкою крапки з комою](https://stackoverflow.com/q/2846283).
@@ -92,7 +94,7 @@ function getGreeting(user) {
ви можете використовувати лапки для задання рядкових літералів як атрибутів:
```js
-const element = ;
+const element = link ;
```
ви також можете використовувати фігурні дужки, щоб вставити вираз JavaScript у атрибут:
@@ -181,4 +183,4 @@ const element = {
>**Порада:**
>
->Ми рекомендуємо використовувати ["Babel" language definition](https://babeljs.io/docs/editors) для вашого редактора, щоб код ES6 та JSX правильно виділявся.
+>Ми рекомендуємо використовувати ["Babel" language definition](https://babeljs.io/docs/en/next/editors) для вашого редактора, щоб код ES6 та JSX правильно виділявся.
diff --git a/content/docs/jsx-in-depth.md b/content/docs/jsx-in-depth.md
index 689fbb899..1e7b2a5db 100644
--- a/content/docs/jsx-in-depth.md
+++ b/content/docs/jsx-in-depth.md
@@ -13,6 +13,12 @@ redirect_from:
- "docs/jsx-in-depth-ko-KR.html"
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+
+
+
JSX — синтаксичний цукор для функції `React.createElement(component, props, ...children)`. Наступний JSX-вираз:
```js
diff --git a/content/docs/legacy-event-pooling.md b/content/docs/legacy-event-pooling.md
new file mode 100644
index 000000000..8fb19c3b3
--- /dev/null
+++ b/content/docs/legacy-event-pooling.md
@@ -0,0 +1,37 @@
+---
+id: legacy-event-pooling
+title: Event Pooling
+permalink: docs/legacy-event-pooling.html
+---
+
+>Note
+>
+>This page is only relevant for React 16 and earlier, and for React Native.
+>
+>React 17 on the web **does not** use event pooling.
+>
+>[Read more](/blog/2020/08/10/react-v17-rc.html#no-event-pooling) about this change in React 17.
+
+The [`SyntheticEvent`](/docs/events.html) objects are pooled. This means that the `SyntheticEvent` object will be reused and all properties will be nullified after the event handler has been called. For example, this won't work:
+
+```javascript
+function handleChange(e) {
+ // This won't work because the event object gets reused.
+ setTimeout(() => {
+ console.log(e.target.value); // Too late!
+ }, 100);
+}
+```
+
+If you need to access event object's properties after the event handler has run, you need to call `e.persist()`:
+
+```javascript
+function handleChange(e) {
+ // Prevents React from resetting its properties:
+ e.persist();
+
+ setTimeout(() => {
+ console.log(e.target.value); // Works
+ }, 100);
+}
+```
diff --git a/content/docs/lifting-state-up.md b/content/docs/lifting-state-up.md
index ea0539e63..38f0cd30c 100644
--- a/content/docs/lifting-state-up.md
+++ b/content/docs/lifting-state-up.md
@@ -9,6 +9,16 @@ redirect_from:
- "docs/flux-todo-list.html"
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Sharing State Between Components](https://react.dev/learn/sharing-state-between-components)
+
+
+
Часто кілька компонентів повинні відображати одні і ті ж змінювані дані. Ми рекомендуємо підняти спільний стан до їхнього найближчого спільного предка. Давайте подивимося, як це працює.
У цьому розділі ми створимо калькулятор температури, який обчислює, чи буде вода закипати при заданій температурі.
@@ -324,7 +334,7 @@ class Calculator extends React.Component {
Якщо щось може бути обчислене або з пропсів, або зі стану, воно, ймовірно, не повинно бути в стані. Наприклад, замість того, щоб зберігати і `celsiusValue`, і `fahrenheitValue`, ми зберігаємо тільки останню редаговану `temperature` і її `scale`. Значення іншого поля вводу завжди може бути обчислено на їх основі у методі `render()`. Це дозволяє очистити або застосувати округлення до іншого поля без втрати будь-якої точності даних, уведених користувачем.
-Коли ви бачите якусь помилку в UI, ви можете скористатися [React Developer Tools](https://github.com/facebook/react/tree/master/packages/react-devtools) для перевірки пропсів і переміститися вгору по дереву, поки не знайдете компонент, відповідальний за оновлення стану. Це дозволяє відслідковувати джерело помилок:
+Коли ви бачите якусь помилку в UI, ви можете скористатися [React Developer Tools](https://github.com/facebook/react/tree/main/packages/react-devtools) для перевірки пропсів і переміститися вгору по дереву, поки не знайдете компонент, відповідальний за оновлення стану. Це дозволяє відслідковувати джерело помилок:
diff --git a/content/docs/lists-and-keys.md b/content/docs/lists-and-keys.md
index 7d7acdcda..812804061 100644
--- a/content/docs/lists-and-keys.md
+++ b/content/docs/lists-and-keys.md
@@ -6,6 +6,17 @@ prev: conditional-rendering.html
next: forms.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Rendering Lists](https://react.dev/learn/rendering-lists)
+
+
+
+
Для початку згадаймо, як перетворювати списки у JavaScript.
У коді, наведеному нижче, ми використовуємо функцію [`map()`](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/map), щоб подвоїти значення в масиві `numbers`. Ми призначаємо новий масив, що повертається з `map()` до змінної `doubled` і виводимо її в консоль:
@@ -36,10 +47,7 @@ const listItems = numbers.map((number) =>
Тепер ми включимо масив `listItems` цілком всередину елемента `
`, і [будемо рендерити його у DOM](/docs/rendering-elements.html#rendering-an-element-into-the-dom):
```javascript{2}
-ReactDOM.render(
-
{listItems}
,
- document.getElementById('root')
-);
+
{listItems}
```
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/GjPyQr?editors=0011)
@@ -64,10 +72,8 @@ function NumberList(props) {
}
const numbers = [1, 2, 3, 4, 5];
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render();
```
Коли ви запустите цей код, ви отримаєте попередження, що для елементів списку має бути вказано ключ. "Ключ" - це спеціальний рядковий атрибут, який потрібно вказувати при створенні списку елементів. Ми обговоримо, чому це важливо, у наступній секції.
@@ -86,12 +92,6 @@ function NumberList(props) {
{listItems}
);
}
-
-const numbers = [1, 2, 3, 4, 5];
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
```
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/jrXYRR?editors=0011)
@@ -130,7 +130,7 @@ const todoItems = todos.map((todo, index) =>
);
```
-Ми не рекомендуємо використовувати індекси для ключів, якщо порядок елементів може змінюватися. Це може негативно вплинути на продуктивність та може викликати проблеми зі станом компонента. Почитайте статтю Робіна Покорни (Robin Pokorny), [яка досконало пояснює, чому індекси-ключі призводять до проблем](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318). Якщо ви вирішите не призначати ключ для елемента в списку, то React за замовчуванням буде використовувати індекси як ключі.
+Ми не рекомендуємо використовувати індекси для ключів, якщо порядок елементів може змінюватися. Це може негативно вплинути на продуктивність та може викликати проблеми зі станом компонента. Почитайте статтю Робіна Покорни (Robin Pokorny), [яка досконало пояснює, чому індекси-ключі призводять до проблем](https://robinpokorny.com/blog/index-as-a-key-is-an-anti-pattern/). Якщо ви вирішите не призначати ключ для елемента в списку, то React за замовчуванням буде використовувати індекси як ключі.
Якщо ви зацікавлені в отриманні додаткової інформації - ось [детальне пояснення того, чому ключі необхідні](/docs/reconciliation.html#recursing-on-children).
@@ -165,12 +165,6 @@ function NumberList(props) {
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React:
+>
+> - [`memo`: Skipping re-rendering when props are unchanged
+](https://react.dev/reference/react/memo#skipping-re-rendering-when-props-are-unchanged)
+
+
+
React за лаштунками використовує кілька розумних підходів для мінімізації кількості вартісних DOM-операцій, необхідних для оновлення користувацького інтерфейсу. Для більшості додатків, використання React дозволить мати швидкий інтерфейс без докладання особливих зусиль для оптимізації продуктивності. Не дивлячись на це, існує кілька шляхів для прискорення швидкодії вашого React-додатку.
## Використання продакшн-збірки {#use-the-production-build}
@@ -43,8 +54,8 @@ npm run build
Ми пропонуємо готові для продакшу версії React та React DOM у вигляді окремих файлів:
```html
-
-
+
+
```
Пам'ятайте, що для продакшну підходять тільки ті файли React, що закінчуються на `.production.min.js`.
@@ -156,32 +167,6 @@ module.exports = {
Пам'ятайте, що це потрібно робити лише для продакшн-збірок. Ви не повинні використовувати `UglifyJsPlugin` чи `TerserPlugin` під час розробки, тому що це приховає корисні попередження від React та сповільнить процес збірки.
-## Профілювання компонентів з використанням вкладки Chrome "Performance" {#profiling-components-with-the-chrome-performance-tab}
-
-У режимі **розробки**, ви можете візуалізувати процес монтування, оновлення і демонтування компонентів, використавши інструменти продуктивності у браузерах, що їх підтримують. Наприклад:
-
-
-
-Щоб зробити це в Chrome:
-
-1. Тимчасово **вимкніть всі розширення Chrome, особливо React DevTools**. Вони можуть істотно спотворити резульати!
-
-2. Впевніться, що додаток запущений в режимі розробки.
-
-3. Відкрийте Chrome DevTools, оберіть вкладку **[Performance](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool)** та натисніть **Record**.
-
-4. Виконайте дії, які потрібно профілювати. Не записуйте більше 20 секунд, інакше Chrome може зависнути.
-
-5. Зупиніть запис.
-
-6. Події React будуть згруповані під міткою **User Timing**.
-
-Для більш детальних інструкцій перегляньте [цю статтю Бена Шварца (Ben Schwarz)](https://calibreapp.com/blog/react-performance-profiling-optimization).
-
-Зверніть увагу на те, **що ці значення відносні і компоненти в продакшні будуть рендеритись швидше**. Проте це допоможе вам зрозуміти, коли не пов'язані між собою частини інтерфейсу оновлюються через помилку та як глибоко і часто ці оновлення вібдуваються.
-
-Наразі Chrome, Edge та IE є єдиними браузерами, котрі підтримують цю функціональність, але ми використовуємо стандарт [User Timing API](https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API), а тому очікуємо, що більше браузерів додадуть її підтримку.
-
## Профілювання компонентів з профайлером DevTools {#profiling-components-with-the-devtools-profiler}
`react-dom` 16.5+ та `react-native` 0.57+ надають додаткові можливості профілювання в режимі розробки з використанням профайлера React DevTools.
@@ -199,6 +184,11 @@ module.exports = {
> Продакшн-збірка профілювання для `react-dom` також доступна як `react-dom/profiling`.
> Докладніше про її використання ви можете дізнатись за посиланням [fb.me/react-profiling](https://fb.me/react-profiling)
+> Note
+>
+> Before React 17, we use the standard [User Timing API](https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API) to profile components with the chrome performance tab.
+> For a more detailed walkthrough, check out [this article by Ben Schwarz](https://calibreapp.com/blog/react-performance-profiling-optimization).
+
## Віртуалізація довгих списків {#virtualize-long-lists}
Якщо ваш додаток рендерить довгі списки даних (сотні чи тисячі рядків), ми радимо використовувати підхід під назвою "віконний доступ". Цей підхід рендерить лише невелику підмножину ваших рядків у будь-який момент часу і може значно зменшити час, потрібний для повторного рендеру компонентів та кількість створених DOM-вузлів.
@@ -379,7 +369,7 @@ function updateColorMap(colormap) {
}
```
-Ця функція була додана до JavaScript у ES2018.
+Ця функція була додана до JavaScript у ES2018.
Якщо ви використовуєте Create React App, то `Object.assign` та розпакування об'єктів доступні за замовчуванням.
diff --git a/content/docs/portals.md b/content/docs/portals.md
index d3ba86821..f26ca4dce 100644
--- a/content/docs/portals.md
+++ b/content/docs/portals.md
@@ -4,6 +4,16 @@ title: Портали
permalink: docs/portals.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [`createPortal`](https://react.dev/reference/react-dom/createPortal)
+
+
+
Портали дозволяють рендерити дочірні елементи в DOM-вузол, який знаходиться за межами DOM-ієрархії батьківського компонента.
```js
@@ -46,7 +56,7 @@ render() {
>
> При роботі з порталами пам'ятайте, що потрібно приділити увагу [управлінню фокусом за допомогою клавіатури](/docs/accessibility.html#programmatically-managing-focus).
>
-> Для модальних діалогів переконайтеся, що будь-який користувач буде здатний взаємодіяти з ними, слідуючи [практикам розробки модальних вікон WAI-ARIA](https://www.w3.org/TR/wai-aria-practices-1.1/#dialog_modal).
+> Для модальних діалогів переконайтеся, що будь-який користувач буде здатний взаємодіяти з ними, слідуючи [практикам розробки модальних вікон WAI-ARIA](https://www.w3.org/WAI/ARIA/apg/patterns/dialogmodal/).
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/yzMaBd)
@@ -146,7 +156,8 @@ function Child() {
);
}
-ReactDOM.render(, appRoot);
+const root = ReactDOM.createRoot(appRoot);
+root.render();
```
[**Спробувати на CodePen**](https://codepen.io/gaearon/pen/jGBWpE)
diff --git a/content/docs/react-without-es6.md b/content/docs/react-without-es6.md
index 004bc3c4d..e88886d52 100644
--- a/content/docs/react-without-es6.md
+++ b/content/docs/react-without-es6.md
@@ -4,6 +4,12 @@ title: React без ES6
permalink: docs/react-without-es6.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+
+
+
Зазвичай, ви б оголосили React-компонент у вигляді JavaScript-класу:
```javascript
@@ -143,11 +149,10 @@ class SayHello extends React.Component {
super(props);
this.state = {message: 'Привіт!'};
}
- // УВАГА: цей синтаксис є експериментальним!
// Тут стрілкова функція виконує прив'язку:
handleClick = () => {
alert(this.state.message);
- }
+ };
render() {
return (
@@ -216,10 +221,8 @@ var TickTock = createReactClass({
}
});
-ReactDOM.render(
- ,
- document.getElementById('example')
-);
+const root = ReactDOM.createRoot(document.getElementById('example'));
+root.render();
```
Якщо компонент використовує декілька міксинів і вони визначають одинакові методи життєвого циклу (наприклад, декілька міксинів хочуть виконати очистку коли компонент буде знищеним), всі методи життєвого циклу будуть гарантовано викликані. Методи, визначені на міксинах, запускаються в порядку перерахування міксинів після виклику методу на компоненті.
diff --git a/content/docs/react-without-jsx.md b/content/docs/react-without-jsx.md
index 37acbbc6e..86e8961f0 100644
--- a/content/docs/react-without-jsx.md
+++ b/content/docs/react-without-jsx.md
@@ -4,6 +4,12 @@ title: React без JSX
permalink: docs/react-without-jsx.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+
+
+
JSX не є вимогою для роботи з React. Використання React без JSX є найзручнішим тоді, коли ви не бажаєте налаштовувати компіляцію у вашому середовищі збірки.
Кожен JSX-елемент являє собою "синтаксичний цукор" для виклику `React.createElement(component, props, ...children)`. Отже, все що можна зробити за допомогою JSX, може також бути виконаним на чистому JavaScript.
@@ -17,10 +23,8 @@ class Hello extends React.Component {
}
}
-ReactDOM.render(
- ,
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render();
```
Його можна переписати таким чином, що JSX не буде використовуватися:
@@ -32,10 +36,8 @@ class Hello extends React.Component {
}
}
-ReactDOM.render(
- React.createElement(Hello, {toWhat: 'світе'}, null),
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(React.createElement(Hello, {toWhat: 'світе'}, null));
```
Якщо ви зацікавлені в інших прикладах того, як JSX компілюється в JavaScript-код, спробуйте [онлайн Babel-компілятор](babel://jsx-simple-example).
@@ -47,10 +49,8 @@ ReactDOM.render(
```js
const e = React.createElement;
-ReactDOM.render(
- e('div', null, 'Привіт, світе'),
- document.getElementById('root')
-);
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(e('div', null, 'Привіт, світе'));
```
Якщо ви використаєте дане скорочення для `React.createElement`, то робота з React без JSX буде такою ж зручною.
diff --git a/content/docs/reconciliation.md b/content/docs/reconciliation.md
index ab8886b8d..047c4cdad 100644
--- a/content/docs/reconciliation.md
+++ b/content/docs/reconciliation.md
@@ -4,6 +4,16 @@ title: Reconciliation
permalink: docs/reconciliation.html
---
+
+
+> These docs are old and won't be updated. Go to [react.dev](https://react.dev/) for the new React docs.
+>
+> These new documentation pages teach modern React and include live examples:
+>
+> - [Preserving and Resetting State](https://react.dev/learn/preserving-and-resetting-state)
+
+
+
React provides a declarative API so that you don'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's "diffing" algorithm so that component updates are predictable while being fast enough for high-performance apps.
## Motivation {#motivation}
@@ -27,7 +37,7 @@ When diffing two trees, React first compares the two root elements. The behavior
Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from `` to ``, or from `` to ``, or from `` to `