diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 028250472..000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,20 +0,0 @@ -version: 2 -jobs: - build: - docker: - - image: circleci/node:12 - steps: - - checkout - - restore_cache: - keys: - - dependencies-{{ checksum "yarn.lock" }} - - run: - name: Install - command: yarn install --pure-lockfile - - save_cache: - paths: - - node_modules - key: dependencies-{{ checksum "yarn.lock" }} - - run: - name: Check Prettier, ESLint, Flow - command: yarn ci-check diff --git a/.eslintignore b/.eslintignore index 942541715..ee6604687 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,5 +1,8 @@ node_modules/* +# Skip beta +beta/* + # Ignore markdown files and examples content/* diff --git a/.flowconfig b/.flowconfig index 836f6ec1e..baf4b0255 100644 --- a/.flowconfig +++ b/.flowconfig @@ -1,5 +1,6 @@ [ignore] +/beta/.* /content/.* /node_modules/.* /public/.* diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d3c569401..150dc2ff0 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,12 +1,10 @@ - - - - + + @@ -77,11 +86,12 @@ next: create-a-new-react-app.html Після **[початкового коду](https://gist.github.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)** додайте два рядки коду в кінці `like_button.js`: -```js{3,4} +```js{3,4,5} // ... початковий код, який ви скопіювали... const domContainer = document.querySelector('#like_button_container'); -ReactDOM.render(e(LikeButton), domContainer); +const root = ReactDOM.createRoot(domContainer); +root.render(e(LikeButton)); ``` Ці два рядки коду шукають `
`, який ми додали до нашого 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 |Blocking Mode |Concurrent Mode | -|--- |--- |--- |--- | -|[String Refs](/docs/refs-and-the-dom.html#legacy-api-string-refs) |✅ |🚫** |🚫** | -|[Legacy Context](/docs/legacy-context.html) |✅ |🚫** |🚫** | -|[findDOMNode](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) |✅ |🚫** |🚫** | -|[Suspense](/docs/concurrent-mode-suspense.html#what-is-suspense-exactly) |✅ |✅ |✅ | -|[SuspenseList](/docs/concurrent-mode-patterns.html#suspenselist) |🚫 |✅ |✅ | -|Suspense SSR + Hydration |🚫 |✅ |✅ | -|Progressive Hydration |🚫 |✅ |✅ | -|Selective Hydration |🚫 |🚫 |✅ | -|Cooperative Multitasking |🚫 |🚫 |✅ | -|Automatic batching of multiple setStates    |🚫* |✅ |✅ | -|[Priority-based Rendering](/docs/concurrent-mode-patterns.html#splitting-high-and-low-priority-state) |🚫 |🚫 |✅ | -|[Interruptible Prerendering](/docs/concurrent-mode-intro.html#interruptible-rendering) |🚫 |🚫 |✅ | -|[useTransition](/docs/concurrent-mode-patterns.html#transitions) |🚫 |🚫 |✅ | -|[useDeferredValue](/docs/concurrent-mode-patterns.html#deferring-a-value) |🚫 |🚫 |✅ | -|[Suspense Reveal "Train"](/docs/concurrent-mode-patterns.html#suspense-reveal-train) |🚫 |🚫 |✅ | - -
- -\*: 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} - - {isPending ? " Loading..." : null} - - -); -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/jovial-lalande-26yep)** - -Now, this feels a lot better! When we click Next, it gets disabled because clicking it multiple times doesn't make sense. And the new "Loading..." tells the user that the app didn't freeze. - -### Reviewing the Changes {#reviewing-the-changes} - -Let's take another look at all the changes we've made since the [original example](https://codesandbox.io/s/infallible-feather-xjtbu): - -```js{3-5,9,11,14,19} -function App() { - const [resource, setResource] = useState(initialResource); - const [startTransition, isPending] = useTransition({ - timeoutMs: 3000 - }); - return ( - <> - - {isPending ? " Loading..." : null} - - - ); -} -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/jovial-lalande-26yep)** - -It took us only seven lines of code to add this transition: - -* We've imported the `useTransition` Hook and used it the component that updates the state. -* We've passed `{timeoutMs: 3000}` to stay on the previous screen for at most 3 seconds. -* We've wrapped our state update into `startTransition` to tell React it's okay to delay it. -* We're using `isPending` to communicate the state transition progress to the user and to disable the button. - -As a result, clicking "Next" doesn't perform an immediate state transition to an "undesirable" loading state, but instead stays on the previous screen and communicates progress there. - -### Where Does the Update Happen? {#where-does-the-update-happen} - -This wasn't very difficult to implement. However, if you start thinking about how this could possibly work, it might become a little mindbending. If we set the state, how come we don't see the result right away? *Where* is the next `` rendering? - -Clearly, both "versions" of `` exist at the same time. We know the old one exists because we see it on the screen and even display a progress indicator on it. And we know the new version also exists *somewhere*, because it's the one that we're waiting for! - -**But how can two versions of the same component exist at the same time?** - -This gets at the root of what Concurrent Mode is. We've [previously said](/docs/concurrent-mode-intro.html#intentional-loading-sequences) it's a bit like React working on state update on a "branch". Another way we can conceptualize is that wrapping a state update in `startTransition` begins rendering it *"in a different universe"*, much like in science fiction movies. We don't "see" that universe directly -- but we can get a signal from it that tells us something is happening (`isPending`). When the update is ready, our "universes" merge back together, and we see the result on the screen! - -Play a bit more with the [demo](https://codesandbox.io/s/jovial-lalande-26yep), and try to imagine it happening. - -Of course, two versions of the tree rendering *at the same time* is an illusion, just like the idea that all programs run on your computer at the same time is an illusion. An operating system switches between different applications very fast. Similarly, React can switch between the version of the tree you see on the screen and the version that it's "preparing" to show next. - -An API like `useTransition` lets you focus on the desired user experience, and not think about the mechanics of how it's implemented. Still, it can be a helpful metaphor to imagine that updates wrapped in `startTransition` happen "on a branch" or "in a different world". - -### Transitions Are Everywhere {#transitions-are-everywhere} - -As we learned from the [Suspense walkthrough](/docs/concurrent-mode-suspense.html), any component can "suspend" any time if some data it needs is not ready yet. We can strategically place `` boundaries in different parts of the tree to handle this, but it won't always be enough. - -Let's get back to our [first Suspense demo](https://codesandbox.io/s/frosty-hermann-bztrp) where there was just one profile. Currently, it fetches the data only once. We'll add a "Refresh" button to check for server updates. - -Our first attempt might look like this: - -```js{6-8,13-15} -const initialResource = fetchUserAndPosts(); - -function ProfilePage() { - const [resource, setResource] = useState(initialResource); - - function handleRefreshClick() { - setResource(fetchUserAndPosts()); - } - - return ( - Loading profile...}> - - - Loading posts...}> - - - - ); -} -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/boring-shadow-100tf)** - -In this example, we start data fetching at the load *and* every time you press "Refresh". We put the result of calling `fetchUserAndPosts()` into state so that components below can start reading the new data from the request we just kicked off. - -We can see in [this example](https://codesandbox.io/s/boring-shadow-100tf) that pressing "Refresh" works. The `` and `` components receive a new `resource` prop that represents the fresh data, they "suspend" because we don't have a response yet, and we see the fallbacks. When the response loads, we can see the updated posts (our fake API adds them every 3 seconds). - -However, the experience feels really jarring. We were browsing a page, but it got replaced by a loading state right as we were interacting with it. It's disorienting. **Just like before, to avoid showing an undesirable loading state, we can wrap the state update in a transition:** - -```js{2-5,9-11,21} -function ProfilePage() { - const [startTransition, isPending] = useTransition({ - // Wait 10 seconds before fallback - timeoutMs: 10000 - }); - const [resource, setResource] = useState(initialResource); - - function handleRefreshClick() { - startTransition(() => { - setResource(fetchProfileData()); - }); - } - - return ( - Loading profile...}> - - - Loading posts...}> - - - - ); -} -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/sleepy-field-mohzb)** - -This feels a lot better! Clicking "Refresh" doesn't pull us away from the page we're browsing anymore. We see something is loading "inline", and when the data is ready, it's displayed. - -### Baking Transitions Into the Design System {#baking-transitions-into-the-design-system} - -We can now see that the need for `useTransition` is *very* common. Pretty much any button click or interaction that can lead to a component suspending needs to be wrapped in `useTransition` to avoid accidentally hiding something the user is interacting with. - -This can lead to a lot of repetitive code across components. This is why **we generally recommend to bake `useTransition` into the *design system* components of your app**. For example, we can extract the transition logic into our own ` - {isPending ? spinner : null} - - ); -} -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/modest-ritchie-iufrh)** - -Note that the button doesn't care *what* state we're updating. It's wrapping *any* state updates that happen during its `onClick` handler into a transition. Now that our ` - Loading posts...}> - - - - ); -} -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/modest-ritchie-iufrh)** - -When a button gets clicked, it starts a transition and calls `props.onClick()` inside of it -- which triggers `handleRefreshClick` in the `` component. We start fetching the fresh data, but it doesn't trigger a fallback because we're inside a transition, and the 10 second timeout specified in the `useTransition` call hasn't passed yet. While a transition is pending, the button displays an inline loading indicator. - -We can see now how Concurrent Mode helps us achieve a good user experience without sacrificing isolation and modularity of components. React coordinates the transition. - -## The Three Steps {#the-three-steps} - -By now we have discussed all of the different visual states that an update may go through. In this section, we will give them names and talk about the progression between them. - -
- -Three steps - -At the very end, we have the **Complete** state. That's where we want to eventually get to. It represents the moment when the next screen is fully rendered and isn't loading more data. - -But before our screen can be Complete, we might need to load some data or code. When we're on the next screen, but some parts of it are still loading, we call that a **Skeleton** state. - -Finally, there are two primary ways that lead us to the Skeleton state. We will illustrate the difference between them with a concrete example. - -### Default: Receded → Skeleton → Complete {#default-receded-skeleton-complete} - -Open [this example](https://codesandbox.io/s/prod-grass-g1lh5) and click "Open Profile". You will see several visual states one by one: - -* **Receded**: For a second, you will see the `

Loading the app...

` fallback. -* **Skeleton:** You will see the `` component with `

Loading posts...

` inside. -* **Complete:** You will see the `` component with no fallbacks inside. Everything was fetched. - -How do we separate the Receded and the Skeleton states? The difference between them is that the **Receded** state feels like "taking a step back" to the user, while the **Skeleton** state feels like "taking a step forward" in our progress to show more content. - -In this example, we started our journey on the ``: - -```js - - {/* previous screen */} - - -``` - -After the click, React started rendering the next screen: - -```js - - {/* next screen */} - - - - - - - -``` - -Both `` and `` need data to render, so they suspend: - -```js{4,6} - - {/* next screen */} - - {/* suspends! */} - Loading posts...}> - {/* suspends! */} - - - -``` - -When a component suspends, React needs to show the closest fallback. But the closest fallback to `` is at the top level: - -```js{2,3,7} - -

Loading the app...

-}> - {/* next screen */} - - {/* suspends! */} - - - - -
-``` - -This is why when we click the button, it feels like we've "taken a step back". The `` boundary which was previously showing useful content (``) had to "recede" to showing the fallback (`

Loading the app...

`). We call that a **Receded** state. - -As we load more data, React will retry rendering, and `` can render successfully. Finally, we're in the **Skeleton** state. We see the new page with missing parts: - -```js{6,7,9} - - {/* next screen */} - - - -

Loading posts...

- }> - {/* suspends! */} -
-
-
-``` - -Eventually, they load too, and we get to the **Complete** state. - -This scenario (Receded → Skeleton → Complete) is the default one. However, the Receded state is not very pleasant because it "hides" existing information. This is why React lets us opt into a different sequence (**Pending** → Skeleton → Complete) with `useTransition`. - -### Preferred: Pending → Skeleton → Complete {#preferred-pending-skeleton-complete} - -When we `useTransition`, React will let us "stay" on the previous screen -- and show a progress indicator there. We call that a **Pending** state. It feels much better than the Receded state because none of our existing content disappears, and the page stays interactive. - -You can compare these two examples to feel the difference: - -* Default: [Receded → Skeleton → Complete](https://codesandbox.io/s/prod-grass-g1lh5) -* **Preferred: [Pending → Skeleton → Complete](https://codesandbox.io/s/focused-snow-xbkvl)** - -The only difference between these two examples is that the first uses regular ` - {isPending ? spinner : null} - - ); -} -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/floral-thunder-iy826)** - -This signals to the user that some work is happening. However, if the transition is relatively short (less than 500ms), it might be too distracting and make the transition itself feel *slower*. - -One possible solution to this is to *delay the spinner itself* from displaying: - -```css -.DelayedSpinner { - animation: 0s linear 0.5s forwards makeVisible; - visibility: hidden; -} - -@keyframes makeVisible { - to { - visibility: visible; - } -} -``` - -```js{2-4,10} -const spinner = ( - - {/* ... */} - -); - -return ( - <> - - {isPending ? spinner : null} - -); -``` - -**[Try it on CodeSandbox](https://codesandbox.io/s/gallant-spence-l6wbk)** - -With this change, even though we're in the Pending state, we don't display any indication to the user until 500ms has passed. This may not seem like much of an improvement when the API responses are slow. But compare how it feels [before](https://codesandbox.io/s/thirsty-liskov-1ygph) and [after](https://codesandbox.io/s/hardcore-http-s18xr) when the API call is fast. Even though the rest of the code hasn't changed, suppressing a "too fast" loading state improves the perceived performance by not calling attention to the delay. - -### Recap {#recap} - -The most important things we learned so far are: - -* By default, our loading sequence is Receded → Skeleton → Complete. -* The Receded state doesn't feel very nice because it hides existing content. -* With `useTransition`, we can opt into showing a Pending state first instead. This will keep us on the previous screen while the next screen is being prepared. -* If we don't want some component to delay the transition, we can wrap it in its own `` boundary. -* Instead of doing `useTransition` in every other component, we can build it into our design system. - -## Other Patterns {#other-patterns} - -Transitions are probably the most common Concurrent Mode pattern you'll encounter, but there are a few more patterns you might find useful. - -### Splitting High and Low Priority State {#splitting-high-and-low-priority-state} - -When you design React components, it is usually best to find the "minimal representation" of state. For example, instead of keeping `firstName`, `lastName`, and `fullName` in state, it's usually better keep only `firstName` and `lastName`, and then calculate `fullName` during rendering. This lets us avoid mistakes where we update one state but forget the other state. - -However, in Concurrent Mode there are cases where you might *want* to "duplicate" some data in different state variables. Consider this tiny translation app: - -```js -const initialQuery = "Hello, world"; -const initialResource = fetchTranslation(initialQuery); - -function App() { - const [query, setQuery] = useState(initialQuery); - const [resource, setResource] = useState(initialResource); - - function handleChange(e) { - const value = e.target.value; - setQuery(value); - setResource(fetchTranslation(value)); - } - - return ( - <> - - Loading...

}> - -
- - ); -} - -function Translation({ resource }) { - return ( -

- {resource.read()} -

- ); -} -``` - -**[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 ( - <> - - {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

Loading profile...

; - } - return ( - <> -

{user.name}

- - - ); -} - -function ProfileTimeline() { - const [posts, setPosts] = useState(null); - - useEffect(() => { - fetchPosts().then(p => setPosts(p)); - }, []); - - if (posts === null) { - return

Loading posts...

; - } - return ( -
    - {posts.map(post => ( -
  • {post.text}
  • - ))} -
- ); -} -``` - -**[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

Loading profile...

; - } - return ( - <> -

{user.name}

- - - ); -} - -// The child doesn't trigger fetching anymore -function ProfileTimeline({ posts }) { - if (posts === null) { - return

Loading posts...

; - } - return ( -
    - {posts.map(post => ( -
  • {post.text}
  • - ))} -
- ); -} -``` - -**[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 ( - <> - - - - ); -} -``` - -**[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 ( - <> - - - - ); -} -``` - -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

Loading profile...

; - } - return ( - <> -

{user.name}

- - - ); -} - -function ProfileTimeline({ id }) { - const [posts, setPosts] = useState(null); - - useEffect(() => { - fetchPosts(id).then(p => setPosts(p)); - }, [id]); - - if (posts === null) { - return

Loading posts...

; - } - return ( -
    - {posts.map(post => ( -
  • {post.text}
  • - ))} -
- ); -} -``` - -**[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

Loading profile...

; - } - return ( - <> -

{user.name}

- - - ); - } -} - -class ProfileTimeline extends React.Component { - state = { - posts: null, - }; - componentDidMount() { - this.fetchData(this.props.id); - } - componentDidUpdate(prevProps) { - if (prevProps.id !== this.props.id) { - this.fetchData(this.props.id); - } - } - async fetchData(id) { - const posts = await fetchPosts(id); - this.setState({ posts }); - } - render() { - const { posts } = this.state; - if (posts === null) { - return

Loading posts...

; - } - return ( -
    - {posts.map(post => ( -
  • {post.text}
  • - ))} -
- ); - } -} -``` - -**[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 ( - <> - - - - ); -} - -function ProfilePage({ resource }) { - return ( - Loading profile...}> - - Loading posts...}> - - - - ); -} - -function ProfileDetails({ resource }) { - const user = resource.user.read(); - return

{user.name}

; -} - -function ProfileTimeline({ resource }) { - const posts = resource.posts.read(); - return ( -
    - {posts.map(post => ( -
  • {post.text}
  • - ))} -
- ); -} -``` - -**[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} - <> - - - -``` - -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) +> - [`