diff --git a/src/content/blog/2022/03/29/react-v18.md b/src/content/blog/2022/03/29/react-v18.md index d21eeb1f50..392c92db57 100644 --- a/src/content/blog/2022/03/29/react-v18.md +++ b/src/content/blog/2022/03/29/react-v18.md @@ -2,156 +2,156 @@ title: "React v18.0" author: The React Team date: 2022/03/08 -description: React 18 is now available on npm! In our last post, we shared step-by-step instructions for upgrading your app to React 18. In this post, we'll give an overview of what's new in React 18, and what it means for the future. +description: React 18 теперь доступен в npm! В нашем последнем посте мы поделились пошаговыми инструкциями по обновлению вашего приложения до React 18. В этом посте мы рассмотрим, что нового появилось в React 18 и что это значит для будущего. --- -March 29, 2022 by [The React Team](/community/team) +29 марта 2022 г. от [Команды React](/community/team) --- -React 18 is now available on npm! In our last post, we shared step-by-step instructions for [upgrading your app to React 18](/blog/2022/03/08/react-18-upgrade-guide). In this post, we'll give an overview of what's new in React 18, and what it means for the future. +React 18 теперь доступен в npm! В нашем последнем посте мы поделились пошаговыми инструкциями по [обновлению вашего приложения до React 18](/blog/2022/03/08/react-18-upgrade-guide). В этом посте мы дадим обзор того, что нового в React 18, и что это значит для будущего. --- -Our latest major version includes out-of-the-box improvements like automatic batching, new APIs like startTransition, and streaming server-side rendering with support for Suspense. +Наша последняя основная версия включает улучшения, доступные "из коробки", такие как автоматическая группировка обновлений (automatic batching), новые API, такие как `startTransition`, и потоковую передачу рендеринга на стороне сервера с поддержкой Suspense. -Many of the features in React 18 are built on top of our new concurrent renderer, a behind-the-scenes change that unlocks powerful new capabilities. Concurrent React is opt-in — it's only enabled when you use a concurrent feature — but we think it will have a big impact on the way people build applications. +Многие из функций React 18 построены на основе нашего нового конкурентного рендерера (concurrent renderer), который является внутренним изменением, открывающим мощные новые возможности. Конкурентный React является опциональным — он включается только тогда, когда вы используете конкурентную функцию — но мы думаем, что он окажет большое влияние на то, как люди создают приложения. -We've spent years researching and developing support for concurrency in React, and we've taken extra care to provide a gradual adoption path for existing users. Last summer, [we formed the React 18 Working Group](/blog/2021/06/08/the-plan-for-react-18) to gather feedback from experts in the community and ensure a smooth upgrade experience for the entire React ecosystem. +Мы потратили годы на исследования и разработку поддержки конкурентности в React, и мы позаботились о том, чтобы предоставить постепенный путь внедрения для существующих пользователей. Прошлым летом [мы сформировали рабочую группу React 18](/blog/2021/06/08/the-plan-for-react-18), чтобы собрать отзывы от экспертов сообщества и обеспечить плавный опыт обновления для всей экосистемы React. -In case you missed it, we shared a lot of this vision at React Conf 2021: +Если вы пропустили, мы поделились многим из этого видения на React Conf 2021: -* In [the keynote](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa), we explain how React 18 fits into our mission to make it easy for developers to build great user experiences -* [Shruti Kapoor](https://twitter.com/shrutikapoor08) [demonstrated how to use the new features in React 18](https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2) -* [Shaundai Person](https://twitter.com/shaundai) gave us an overview of [streaming server rendering with Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3) +* В [основном докладе](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa) мы объясняем, как React 18 вписывается в нашу миссию по упрощению создания отличного пользовательского опыта для разработчиков. +* [Шрути Капур (Shruti Kapoor)](https://twitter.com/shrutikapoor08) [продемонстрировала, как использовать новые функции в React 18](https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2). +* [Шаундай Персон (Shaundai Person)](https://twitter.com/shaundai) представила нам обзор [потоковой передачи рендеринга на стороне сервера с Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3). -Below is a full overview of what to expect in this release, starting with Concurrent Rendering. +Ниже представлен полный обзор того, что ожидать в этом релизе, начиная с конкурентного рендеринга. -For React Native users, React 18 will ship in React Native with the New React Native Architecture. For more information, see the [React Conf keynote here](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s). +Для пользователей React Native, React 18 будет поставляться с новой архитектурой React Native. Для получения дополнительной информации, см. [основной доклад React Conf здесь](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s). -## What is Concurrent React? {/*what-is-concurrent-react*/} +## Что такое конкурентный React? {/*what-is-concurrent-react*/} -The most important addition in React 18 is something we hope you never have to think about: concurrency. We think this is largely true for application developers, though the story may be a bit more complicated for library maintainers. +Самое важное дополнение в React 18 — это то, о чем мы надеемся, вы никогда не будете думать: конкурентность. Мы думаем, что это в значительной степени верно для разработчиков приложений, хотя для сопровождающих библиотек ситуация может быть немного сложнее. -Concurrency is not a feature, per se. It's a new behind-the-scenes mechanism that enables React to prepare multiple versions of your UI at the same time. You can think of concurrency as an implementation detail — it's valuable because of the features that it unlocks. React uses sophisticated techniques in its internal implementation, like priority queues and multiple buffering. But you won't see those concepts anywhere in our public APIs. +Конкурентность — это не функция как таковая. Это новый внутренний механизм, который позволяет React одновременно подготавливать несколько версий вашего пользовательского интерфейса. Вы можете думать о конкурентности как о детали реализации — она ценна из-за функций, которые она открывает. React использует сложные методы в своей внутренней реализации, такие как очереди с приоритетами и множественное буферирование. Но вы не увидите этих концепций в наших публичных API. -When we design APIs, we try to hide implementation details from developers. As a React developer, you focus on *what* you want the user experience to look like, and React handles *how* to deliver that experience. So we don’t expect React developers to know how concurrency works under the hood. +Когда мы разрабатываем API, мы стараемся скрыть детали реализации от разработчиков. Как разработчик React, вы фокусируетесь на том, *каким* вы хотите видеть пользовательский опыт, а React обрабатывает *то, как* этот опыт будет доставлен. Поэтому мы не ожидаем, что разработчики React будут знать, как работает конкурентность "под капотом". -However, Concurrent React is more important than a typical implementation detail — it's a foundational update to React's core rendering model. So while it's not super important to know how concurrency works, it may be worth knowing what it is at a high level. +Однако конкурентный React важнее обычной детали реализации — это фундаментальное обновление основной модели рендеринга React. Поэтому, хотя знать, как работает конкурентность, не очень важно, возможно, стоит знать, что это такое на высоком уровне. -A key property of Concurrent React is that rendering is interruptible. When you first upgrade to React 18, before adding any concurrent features, updates are rendered the same as in previous versions of React — in a single, uninterrupted, synchronous transaction. With synchronous rendering, once an update starts rendering, nothing can interrupt it until the user can see the result on screen. +Ключевым свойством конкурентного React является то, что рендеринг может быть прерван. Когда вы впервые обновляетесь до React 18, прежде чем добавлять какие-либо конкурентные функции, обновления рендерятся так же, как и в предыдущих версиях React — в одной, непрерывной, синхронной транзакции. При синхронном рендеринге, как только обновление начинает рендериться, ничто не может его прервать, пока пользователь не увидит результат на экране. -In a concurrent render, this is not always the case. React may start rendering an update, pause in the middle, then continue later. It may even abandon an in-progress render altogether. React guarantees that the UI will appear consistent even if a render is interrupted. To do this, it waits to perform DOM mutations until the end, once the entire tree has been evaluated. With this capability, React can prepare new screens in the background without blocking the main thread. This means the UI can respond immediately to user input even if it’s in the middle of a large rendering task, creating a fluid user experience. +В конкурентном рендеринге это не всегда так. React может начать рендерить обновление, приостановиться посередине, а затем продолжить позже. Он может даже полностью отказаться от рендеринга в процессе. React гарантирует, что пользовательский интерфейс будет выглядеть последовательно, даже если рендеринг прерван. Для этого он ждет выполнения мутаций DOM до конца, после того как все дерево будет оценено. Благодаря этой возможности React может подготавливать новые экраны в фоновом режиме, не блокируя основной поток. Это означает, что пользовательский интерфейс может немедленно реагировать на ввод пользователя, даже если он находится в середине большой задачи рендеринга, создавая плавный пользовательский опыт. -Another example is reusable state. Concurrent React can remove sections of the UI from the screen, then add them back later while reusing the previous state. For example, when a user tabs away from a screen and back, React should be able to restore the previous screen in the same state it was in before. In an upcoming minor, we're planning to add a new component called `` that implements this pattern. Similarly, you’ll be able to use Offscreen to prepare new UI in the background so that it’s ready before the user reveals it. +Другим примером является повторно используемое состояние. Конкурентный React может удалять части пользовательского интерфейса с экрана, а затем снова добавлять их позже, повторно используя предыдущее состояние. Например, когда пользователь переключается с экрана и возвращается обратно, React должен иметь возможность восстановить предыдущий экран в том же состоянии, в котором он был до этого. В предстоящем минорном релизе мы планируем добавить новый компонент под названием ``, который реализует этот шаблон. Аналогично, вы сможете использовать `Offscreen` для подготовки нового пользовательского интерфейса в фоновом режиме, чтобы он был готов до того, как пользователь его отобразит. -Concurrent rendering is a powerful new tool in React and most of our new features are built to take advantage of it, including Suspense, transitions, and streaming server rendering. But React 18 is just the beginning of what we aim to build on this new foundation. +Конкурентный рендеринг — это мощный новый инструмент в React, и большинство наших новых функций созданы для его использования, включая Suspense, переходы (transitions) и потоковую передачу рендеринга на стороне сервера. Но React 18 — это только начало того, что мы стремимся построить на этом новом фундаменте. -## Gradually Adopting Concurrent Features {/*gradually-adopting-concurrent-features*/} +## Постепенное внедрение конкурентных функций {/*gradually-adopting-concurrent-features*/} -Technically, concurrent rendering is a breaking change. Because concurrent rendering is interruptible, components behave slightly differently when it is enabled. +Технически, конкурентный рендеринг является обратно несовместимым изменением. Поскольку конкурентный рендеринг может быть прерван, компоненты ведут себя немного иначе, когда он включен. -In our testing, we've upgraded thousands of components to React 18. What we've found is that nearly all existing components "just work" with concurrent rendering, without any changes. However, some of them may require some additional migration effort. Although the changes are usually small, you'll still have the ability to make them at your own pace. The new rendering behavior in React 18 is **only enabled in the parts of your app that use new features.** +В ходе нашего тестирования мы обновили тысячи компонентов до React 18. Мы обнаружили, что почти все существующие компоненты "просто работают" с конкурентным рендерингом без каких-либо изменений. Однако некоторые из них могут потребовать дополнительных усилий по миграции. Хотя изменения обычно незначительны, у вас все равно будет возможность вносить их в удобном для вас темпе. Новое поведение рендеринга в React 18 **включено только в тех частях вашего приложения, которые используют новые функции.** -The overall upgrade strategy is to get your application running on React 18 without breaking existing code. Then you can gradually start adding concurrent features at your own pace. You can use [``](/reference/react/StrictMode) to help surface concurrency-related bugs during development. Strict Mode doesn't affect production behavior, but during development it will log extra warnings and double-invoke functions that are expected to be idempotent. It won't catch everything, but it's effective at preventing the most common types of mistakes. +Общая стратегия обновления заключается в том, чтобы ваше приложение работало на React 18 без нарушения существующего кода. Затем вы можете постепенно начать добавлять конкурентные функции в удобном для вас темпе. Вы можете использовать [``](/reference/react/StrictMode) для помощи в выявлении ошибок, связанных с конкурентностью, во время разработки. Strict Mode не влияет на поведение в продакшене, но во время разработки он будет выводить дополнительные предупреждения и дважды вызывать функции, которые должны быть идемпотентными. Он не обнаружит все, но будет эффективен в предотвращении наиболее распространенных типов ошибок. -After you upgrade to React 18, you’ll be able to start using concurrent features immediately. For example, you can use startTransition to navigate between screens without blocking user input. Or useDeferredValue to throttle expensive re-renders. +После обновления до React 18 вы сможете немедленно начать использовать конкурентные функции. Например, вы можете использовать `startTransition` для навигации между экранами без блокировки ввода пользователя. Или `useDeferredValue` для замедления дорогостоящих повторных рендеров. -However, long term, we expect the main way you’ll add concurrency to your app is by using a concurrent-enabled library or framework. In most cases, you won’t interact with concurrent APIs directly. For example, instead of developers calling startTransition whenever they navigate to a new screen, router libraries will automatically wrap navigations in startTransition. +Однако в долгосрочной перспективе мы ожидаем, что основным способом добавления конкурентности в ваше приложение будет использование совместимой с конкурентностью библиотеки или фреймворка. В большинстве случаев вы не будете напрямую взаимодействовать с конкурентными API. Например, вместо того чтобы разработчики вызывали `startTransition` каждый раз, когда они переходят на новый экран, библиотеки маршрутизации будут автоматически оборачивать навигации в `startTransition`. -It may take some time for libraries to upgrade to be concurrent compatible. We’ve provided new APIs to make it easier for libraries to take advantage of concurrent features. In the meantime, please be patient with maintainers as we work to gradually migrate the React ecosystem. +Библиотекам может потребоваться некоторое время для обновления, чтобы стать совместимыми с конкурентностью. Мы предоставили новые API, чтобы упростить библиотекам использование конкурентных функций. А пока, пожалуйста, будьте терпеливы с сопровождающими, пока мы работаем над постепенной миграцией экосистемы React. -For more info, see our previous post: [How to upgrade to React 18](/blog/2022/03/08/react-18-upgrade-guide). +Для получения дополнительной информации см. наш предыдущий пост: [Как обновиться до React 18](/blog/2022/03/08/react-18-upgrade-guide). -## Suspense in Data Frameworks {/*suspense-in-data-frameworks*/} +## Suspense в фреймворках для работы с данными {/*suspense-in-data-frameworks*/} -In React 18, you can start using [Suspense](/reference/react/Suspense) for data fetching in opinionated frameworks like Relay, Next.js, Hydrogen, or Remix. Ad hoc data fetching with Suspense is technically possible, but still not recommended as a general strategy. +В React 18 вы можете начать использовать [Suspense](/reference/react/Suspense) для получения данных в специализированных фреймворках, таких как Relay, Next.js, Hydrogen или Remix. Получение данных "ad hoc" с помощью Suspense технически возможно, но все еще не рекомендуется в качестве общей стратегии. -In the future, we may expose additional primitives that could make it easier to access your data with Suspense, perhaps without the use of an opinionated framework. However, Suspense works best when it’s deeply integrated into your application’s architecture: your router, your data layer, and your server rendering environment. So even long term, we expect that libraries and frameworks will play a crucial role in the React ecosystem. +В будущем мы можем предоставить дополнительные примитивы, которые могут упростить доступ к вашим данным с помощью Suspense, возможно, без использования специализированного фреймворка. Однако Suspense лучше всего работает, когда он глубоко интегрирован в архитектуру вашего приложения: ваш маршрутизатор, ваш слой данных и ваша среда рендеринга на сервере. Поэтому даже в долгосрочной перспективе мы ожидаем, что библиотеки и фреймворки будут играть решающую роль в экосистеме React. -As in previous versions of React, you can also use Suspense for code splitting on the client with React.lazy. But our vision for Suspense has always been about much more than loading code — the goal is to extend support for Suspense so that eventually, the same declarative Suspense fallback can handle any asynchronous operation (loading code, data, images, etc). +Как и в предыдущих версиях React, вы также можете использовать Suspense для разделения кода на стороне клиента с помощью `React.lazy`. Но наше видение Suspense всегда было больше, чем просто загрузка кода — цель состоит в том, чтобы расширить поддержку Suspense, чтобы в конечном итоге один и тот же декларативный запасной вариант (fallback) Suspense мог обрабатывать любую асинхронную операцию (загрузку кода, данных, изображений и т. д.). -## Server Components is Still in Development {/*server-components-is-still-in-development*/} +## Server Components все еще в разработке {/*server-components-is-still-in-development*/} -[**Server Components**](/blog/2020/12/21/data-fetching-with-react-server-components) is an upcoming feature that allows developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering. Server Components is not inherently coupled to Concurrent React, but it’s designed to work best with concurrent features like Suspense and streaming server rendering. +[**Server Components**](/blog/2020/12/21/data-fetching-with-react-server-components) — это предстоящая функция, которая позволяет разработчикам создавать приложения, охватывающие сервер и клиент, сочетая богатую интерактивность клиентских приложений с улучшенной производительностью традиционного серверного рендеринга. Server Components не связаны напрямую с Concurrent React, но они разработаны для лучшей работы с конкурентными функциями, такими как Suspense и потоковая передача рендеринга на сервере. -Server Components is still experimental, but we expect to release an initial version in a minor 18.x release. In the meantime, we’re working with frameworks like Next.js, Hydrogen, and Remix to advance the proposal and get it ready for broad adoption. +Server Components все еще находятся в экспериментальной стадии, но мы ожидаем выпустить первоначальную версию в минорном релизе 18.x. А пока мы работаем с фреймворками, такими как Next.js, Hydrogen и Remix, над продвижением предложения и подготовкой его к широкому внедрению. -## What's New in React 18 {/*whats-new-in-react-18*/} +## Что нового в React 18 {/*whats-new-in-react-18*/} -### New Feature: Automatic Batching {/*new-feature-automatic-batching*/} +### Новая функция: Автоматическая группировка обновлений {/*new-feature-automatic-batching*/} -Batching is when React groups multiple state updates into a single re-render for better performance. Without automatic batching, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default. With automatic batching, these updates will be batched automatically: +Группировка обновлений (Batching) — это когда React объединяет несколько обновлений состояния в один повторный рендер для повышения производительности. Без автоматической группировки мы группировали обновления только внутри обработчиков событий React. Обновления внутри промисов, `setTimeout`, нативных обработчиков событий или любых других событий по умолчанию не группировались в React. С автоматической группировкой эти обновления будут группироваться автоматически: ```js -// Before: only React events were batched. +// До: группировались только события React. setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); - // React will render twice, once for each state update (no batching) + // React будет рендерить дважды, по одному разу для каждого обновления состояния (без группировки) }, 1000); -// After: updates inside of timeouts, promises, -// native event handlers or any other event are batched. +// После: обновления внутри тайм-аутов, промисов, +// нативных обработчиков событий или любых других событий группируются. setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // React будет перерисовываться только один раз в конце (это группировка!) }, 1000); ``` -For more info, see this post for [Automatic batching for fewer renders in React 18](https://github.com/reactwg/react-18/discussions/21). +Для получения дополнительной информации см. этот пост [Automatic batching for fewer renders in React 18](https://github.com/reactwg/react-18/discussions/21). -### New Feature: Transitions {/*new-feature-transitions*/} +### Новая функция: Переходы {/*new-feature-transitions*/} -A transition is a new concept in React to distinguish between urgent and non-urgent updates. +Переход (Transition) — это новая концепция в React для различения срочных и несрочных обновлений. -* **Urgent updates** reflect direct interaction, like typing, clicking, pressing, and so on. -* **Transition updates** transition the UI from one view to another. +* **Срочные обновления** отражают прямое взаимодействие, такое как ввод текста, нажатие кнопки и т. д. +* **Переходы** переводят пользовательский интерфейс из одного вида в другой. -Urgent updates like typing, clicking, or pressing, need immediate response to match our intuitions about how physical objects behave. Otherwise they feel "wrong". However, transitions are different because the user doesn’t expect to see every intermediate value on screen. +Срочные обновления, такие как ввод текста, нажатие кнопки или клавиши, требуют немедленного ответа, чтобы соответствовать нашим интуитивным представлениям о поведении физических объектов. В противном случае они ощущаются "неправильными". Однако переходы отличаются, потому что пользователь не ожидает видеть каждое промежуточное значение на экране. -For example, when you select a filter in a dropdown, you expect the filter button itself to respond immediately when you click. However, the actual results may transition separately. A small delay would be imperceptible and often expected. And if you change the filter again before the results are done rendering, you only care to see the latest results. +Например, когда вы выбираете фильтр в выпадающем списке, вы ожидаете, что сама кнопка фильтра отреагирует немедленно при нажатии. Однако фактические результаты могут переходить отдельно. Небольшая задержка будет незаметной и часто ожидаемой. И если вы снова измените фильтр до того, как результаты будут полностью отрисованы, вас будут интересовать только последние результаты. -Typically, for the best user experience, a single user input should result in both an urgent update and a non-urgent one. You can use startTransition API inside an input event to inform React which updates are urgent and which are "transitions": +Как правило, для наилучшего пользовательского опыта одно взаимодействие с пользователем должно приводить как к срочному, так и к несрочному обновлению. Вы можете использовать API `startTransition` внутри события ввода, чтобы сообщить React, какие обновления являются срочными, а какие — "переходами": ```js import { startTransition } from 'react'; -// Urgent: Show what was typed +// Срочное: Показать, что было введено setInputValue(input); -// Mark any state updates inside as transitions +// Пометить все обновления состояния внутри как переходы startTransition(() => { - // Transition: Show the results + // Переход: Показать результаты setSearchQuery(input); }); ``` -Updates wrapped in startTransition are handled as non-urgent and will be interrupted if more urgent updates like clicks or key presses come in. If a transition gets interrupted by the user (for example, by typing multiple characters in a row), React will throw out the stale rendering work that wasn’t finished and render only the latest update. +Обновления, обернутые в `startTransition`, обрабатываются как несрочные и будут прерваны, если поступят более срочные обновления, такие как клики или нажатия клавиш. Если переход прерывается пользователем (например, при вводе нескольких символов подряд), React отбросит устаревшую работу по рендерингу, которая не была завершена, и отрендерит только последнее обновление. -* `useTransition`: a Hook to start transitions, including a value to track the pending state. -* `startTransition`: a method to start transitions when the Hook cannot be used. +* `useTransition`: хук для запуска переходов, включая значение для отслеживания состояния ожидания. +* `startTransition`: метод для запуска переходов, когда хук не может быть использован. -Transitions will opt in to concurrent rendering, which allows the update to be interrupted. If the content re-suspends, transitions also tell React to continue showing the current content while rendering the transition content in the background (see the [Suspense RFC](https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md) for more info). +Переходы будут использовать конкурентный рендеринг, который позволяет прерывать обновление. Если контент повторно приостанавливается (suspends), переходы также сообщают React о необходимости продолжать отображать текущий контент во время рендеринга контента перехода в фоновом режиме (см. [RFC Suspense](https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md) для получения дополнительной информации). -[See docs for transitions here](/reference/react/useTransition). +[См. документацию по переходам здесь](/reference/react/useTransition). -### New Suspense Features {/*new-suspense-features*/} +### Новые функции Suspense {/*new-suspense-features*/} -Suspense lets you declaratively specify the loading state for a part of the component tree if it's not yet ready to be displayed: +Suspense позволяет декларативно указывать состояние загрузки для части дерева компонентов, если оно еще не готово к отображению: ```js }> @@ -159,186 +159,185 @@ Suspense lets you declaratively specify the loading state for a part of the comp ``` -Suspense makes the "UI loading state" a first-class declarative concept in the React programming model. This lets us build higher-level features on top of it. +Suspense делает "состояние загрузки пользовательского интерфейса" первоклассной декларативной концепцией в модели программирования React. Это позволяет нам создавать на его основе функции более высокого уровня. -We introduced a limited version of Suspense several years ago. However, the only supported use case was code splitting with React.lazy, and it wasn't supported at all when rendering on the server. +Мы представили ограниченную версию Suspense несколько лет назад. Однако единственным поддерживаемым сценарием использования было разделение кода с помощью `React.lazy`, и оно вообще не поддерживалось при рендеринге на сервере. -In React 18, we've added support for Suspense on the server and expanded its capabilities using concurrent rendering features. +В React 18 мы добавили поддержку Suspense на сервере и расширили его возможности с использованием функций конкурентного рендеринга. -Suspense in React 18 works best when combined with the transition API. If you suspend during a transition, React will prevent already-visible content from being replaced by a fallback. Instead, React will delay the render until enough data has loaded to prevent a bad loading state. +Suspense в React 18 лучше всего работает в сочетании с API переходов. Если вы приостанавливаетесь во время перехода, React предотвратит замену уже видимого контента запасным вариантом (fallback). Вместо этого React отложит рендеринг до тех пор, пока не будет загружено достаточно данных, чтобы избежать плохого состояния загрузки. -For more, see the RFC for [Suspense in React 18](https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md). +Подробнее см. в RFC для [Suspense в React 18](https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md). -### New Client and Server Rendering APIs {/*new-client-and-server-rendering-apis*/} +### Новые API для рендеринга на клиенте и сервере {/*new-client-and-server-rendering-apis*/} -In this release we took the opportunity to redesign the APIs we expose for rendering on the client and server. These changes allow users to continue using the old APIs in React 17 mode while they upgrade to the new APIs in React 18. +В этом релизе мы воспользовались возможностью переработать API, которые мы предоставляем для рендеринга на клиенте и сервере. Эти изменения позволяют пользователям продолжать использовать старые API в режиме React 17 во время обновления до новых API в React 18. #### React DOM Client {/*react-dom-client*/} -These new APIs are now exported from `react-dom/client`: +Эти новые API теперь экспортируются из `react-dom/client`: -* `createRoot`: New method to create a root to `render` or `unmount`. Use it instead of `ReactDOM.render`. New features in React 18 don't work without it. -* `hydrateRoot`: New method to hydrate a server rendered application. Use it instead of `ReactDOM.hydrate` in conjunction with the new React DOM Server APIs. New features in React 18 don't work without it. +* `createRoot`: Новый метод для создания корневого узла для `render` или `unmount`. Используйте его вместо `ReactDOM.render`. Новые функции в React 18 не работают без него. +* `hydrateRoot`: Новый метод для гидратации приложения, отрендеренного на сервере. Используйте его вместо `ReactDOM.hydrate` в сочетании с новыми API React DOM Server. Новые функции в React 18 не работают без него. -Both `createRoot` and `hydrateRoot` accept a new option called `onRecoverableError` in case you want to be notified when React recovers from errors during rendering or hydration for logging. By default, React will use [`reportError`](https://developer.mozilla.org/en-US/docs/Web/API/reportError), or `console.error` in the older browsers. +И `createRoot`, и `hydrateRoot` принимают новую опцию `onRecoverableError` на случай, если вы хотите получать уведомления, когда React восстанавливается после ошибок во время рендеринга или гидратации для логирования. По умолчанию React будет использовать [`reportError`](https://developer.mozilla.org/en-US/docs/Web/API/reportError) или `console.error` в старых браузерах. -[See docs for React DOM Client here](/reference/react-dom/client). +[См. документацию по React DOM Client здесь](/reference/react-dom/client). #### React DOM Server {/*react-dom-server*/} -These new APIs are now exported from `react-dom/server` and have full support for streaming Suspense on the server: +Эти новые API теперь экспортируются из `react-dom/server` и имеют полную поддержку потоковой передачи Suspense на сервере: -* `renderToPipeableStream`: for streaming in Node environments. -* `renderToReadableStream`: for modern edge runtime environments, such as Deno and Cloudflare workers. +* `renderToPipeableStream`: для потоковой передачи в средах Node. +* `renderToReadableStream`: для современных сред выполнения на границе сети (edge runtime), таких как Deno и Cloudflare workers. -The existing `renderToString` method keeps working but is discouraged. +Существующий метод `renderToString` продолжает работать, но не рекомендуется. -[See docs for React DOM Server here](/reference/react-dom/server). +[См. документацию по React DOM Server здесь](/reference/react-dom/server). -### New Strict Mode Behaviors {/*new-strict-mode-behaviors*/} +### Новое поведение Strict Mode {/*new-strict-mode-behaviors*/} -In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React would unmount and remount trees using the same component state as before. +В будущем мы хотели бы добавить функцию, которая позволит React добавлять и удалять части пользовательского интерфейса, сохраняя при этом состояние. Например, когда пользователь переключается с экрана и возвращается обратно, React должен иметь возможность немедленно отобразить предыдущий экран. Для этого React будет размонтировать и повторно монтировать деревья, используя то же состояние компонента, что и раньше. -This feature will give React apps better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects assume they are only mounted or destroyed once. +Эта функция обеспечит лучшую производительность приложений React "из коробки", но требует, чтобы компоненты были устойчивы к многократному монтированию и уничтожению эффектов. Большинство эффектов будут работать без изменений, но некоторые эффекты предполагают, что они монтируются и уничтожаются только один раз. -To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount. +Чтобы помочь выявить эти проблемы, React 18 вводит новую проверку в Strict Mode, предназначенную только для разработки. Эта новая проверка будет автоматически размонтировать и повторно монтировать каждый компонент, когда компонент монтируется впервые, восстанавливая предыдущее состояние при втором монтировании. -Before this change, React would mount the component and create the effects: +До этого изменения React монтировал компонент и создавал эффекты: ``` -* React mounts the component. - * Layout effects are created. - * Effects are created. +* React монтирует компонент. + * Создаются эффекты макета (Layout effects). + * Создаются эффекты (Effects). ``` - -With Strict Mode in React 18, React will simulate unmounting and remounting the component in development mode: +Со Strict Mode в React 18 React будет симулировать размонтирование и повторное монтирование компонента в режиме разработки: ``` -* React mounts the component. - * Layout effects are created. - * Effects are created. -* React simulates unmounting the component. - * Layout effects are destroyed. - * Effects are destroyed. -* React simulates mounting the component with the previous state. - * Layout effects are created. - * Effects are created. +* React монтирует компонент. + * Создаются эффекты макета (Layout effects). + * Создаются эффекты (Effects). +* React симулирует размонтирование компонента. + * Уничтожаются эффекты макета (Layout effects). + * Уничтожаются эффекты (Effects). +* React симулирует монтирование компонента с предыдущим состоянием. + * Создаются эффекты макета (Layout effects). + * Создаются эффекты (Effects). ``` -[See docs for ensuring reusable state here](/reference/react/StrictMode#fixing-bugs-found-by-re-running-effects-in-development). +[См. документацию по обеспечению повторно используемого состояния здесь](/reference/react/StrictMode#fixing-bugs-found-by-re-running-effects-in-development). -### New Hooks {/*new-hooks*/} +### Новые хуки {/*new-hooks*/} #### useId {/*useid*/} -`useId` is a new Hook for generating unique IDs on both the client and server, while avoiding hydration mismatches. It is primarily useful for component libraries integrating with accessibility APIs that require unique IDs. This solves an issue that already exists in React 17 and below, but it's even more important in React 18 because of how the new streaming server renderer delivers HTML out-of-order. [See docs here](/reference/react/useId). +`useId` — это новый хук для генерации уникальных идентификаторов как на клиенте, так и на сервере, избегая при этом несоответствий при гидратации. Он в основном полезен для библиотек компонентов, интегрирующихся с API доступности, требующими уникальных идентификаторов. Это решает проблему, которая уже существует в React 17 и ниже, но становится еще более важной в React 18 из-за того, как новый потоковый серверный рендерер доставляет HTML вне порядка. [См. документацию здесь](/reference/react/useId). -> Note +> Примечание > -> `useId` is **not** for generating [keys in a list](/learn/rendering-lists#where-to-get-your-key). Keys should be generated from your data. +> `useId` **не** предназначен для генерации [ключей в списке](/learn/rendering-lists#where-to-get-your-key). Ключи должны генерироваться из ваших данных. #### useTransition {/*usetransition*/} -`useTransition` and `startTransition` let you mark some state updates as not urgent. Other state updates are considered urgent by default. React will allow urgent state updates (for example, updating a text input) to interrupt non-urgent state updates (for example, rendering a list of search results). [See docs here](/reference/react/useTransition). +`useTransition` и `startTransition` позволяют помечать некоторые обновления состояния как несрочные. Другие обновления состояния по умолчанию считаются срочными. React позволит срочным обновлениям состояния (например, обновлению текстового поля) прерывать несрочные обновления состояния (например, рендеринг списка результатов поиска). [См. документацию здесь](/reference/react/useTransition). #### useDeferredValue {/*usedeferredvalue*/} -`useDeferredValue` lets you defer re-rendering a non-urgent part of the tree. It is similar to debouncing, but has a few advantages compared to it. There is no fixed time delay, so React will attempt the deferred render right after the first render is reflected on the screen. The deferred render is interruptible and doesn't block user input. [See docs here](/reference/react/useDeferredValue). +`useDeferredValue` позволяет отложить повторный рендеринг несрочной части дерева. Это похоже на "debouncing", но имеет несколько преимуществ по сравнению с ним. Нет фиксированной временной задержки, поэтому React попытается отложенный рендеринг сразу после того, как первый рендер будет отражен на экране. Отложенный рендеринг может быть прерван и не блокирует ввод пользователя. [См. документацию здесь](/reference/react/useDeferredValue). #### useSyncExternalStore {/*usesyncexternalstore*/} -`useSyncExternalStore` is a new Hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. It removes the need for useEffect when implementing subscriptions to external data sources, and is recommended for any library that integrates with state external to React. [See docs here](/reference/react/useSyncExternalStore). +`useSyncExternalStore` — это новый хук, который позволяет внешним хранилищам поддерживать конкурентные чтения, принудительно синхронизируя обновления хранилища. Он устраняет необходимость в `useEffect` при реализации подписок на внешние источники данных и рекомендуется для любых библиотек, которые интегрируются с состоянием вне React. [См. документацию здесь](/reference/react/useSyncExternalStore). -> Note +> Примечание > -> `useSyncExternalStore` is intended to be used by libraries, not application code. +> `useSyncExternalStore` предназначен для использования библиотеками, а не кодом приложения. #### useInsertionEffect {/*useinsertioneffect*/} -`useInsertionEffect` is a new Hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you’ve already built a CSS-in-JS library we don’t expect you to ever use this. This Hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout. [See docs here](/reference/react/useInsertionEffect). +`useInsertionEffect` — это новый хук, который позволяет библиотекам CSS-in-JS решать проблемы производительности при внедрении стилей во время рендеринга. Если вы еще не создали библиотеку CSS-in-JS, мы не ожидаем, что вы когда-либо будете использовать это. Этот хук будет выполняться после мутации DOM, но до того, как эффекты макета (layout effects) прочитают новый макет. Это решает проблему, которая уже существует в React 17 и ниже, но становится еще более важной в React 18, поскольку React уступает управление браузеру во время конкурентного рендеринга, давая ему возможность пересчитать макет. [См. документацию здесь](/reference/react/useInsertionEffect). -> Note +> Примечание > -> `useInsertionEffect` is intended to be used by libraries, not application code. +> `useInsertionEffect` предназначен для использования библиотеками, а не кодом приложения. -## How to Upgrade {/*how-to-upgrade*/} +## Как обновиться {/*how-to-upgrade*/} -See [How to Upgrade to React 18](/blog/2022/03/08/react-18-upgrade-guide) for step-by-step instructions and a full list of breaking and notable changes. +См. [Как обновиться до React 18](/blog/2022/03/08/react-18-upgrade-guide) для пошаговых инструкций и полного списка обратно несовместимых и значительных изменений. -## Changelog {/*changelog*/} +## Журнал изменений {/*changelog*/} ### React {/*react*/} -* Add `useTransition` and `useDeferredValue` to separate urgent updates from transitions. ([#10426](https://github.com/facebook/react/pull/10426), [#10715](https://github.com/facebook/react/pull/10715), [#15593](https://github.com/facebook/react/pull/15593), [#15272](https://github.com/facebook/react/pull/15272), [#15578](https://github.com/facebook/react/pull/15578), [#15769](https://github.com/facebook/react/pull/15769), [#17058](https://github.com/facebook/react/pull/17058), [#18796](https://github.com/facebook/react/pull/18796), [#19121](https://github.com/facebook/react/pull/19121), [#19703](https://github.com/facebook/react/pull/19703), [#19719](https://github.com/facebook/react/pull/19719), [#19724](https://github.com/facebook/react/pull/19724), [#20672](https://github.com/facebook/react/pull/20672), [#20976](https://github.com/facebook/react/pull/20976) by [@acdlite](https://github.com/acdlite), [@lunaruan](https://github.com/lunaruan), [@rickhanlonii](https://github.com/rickhanlonii), and [@sebmarkbage](https://github.com/sebmarkbage)) -* Add `useId` for generating unique IDs. ([#17322](https://github.com/facebook/react/pull/17322), [#18576](https://github.com/facebook/react/pull/18576), [#22644](https://github.com/facebook/react/pull/22644), [#22672](https://github.com/facebook/react/pull/22672), [#21260](https://github.com/facebook/react/pull/21260) by [@acdlite](https://github.com/acdlite), [@lunaruan](https://github.com/lunaruan), and [@sebmarkbage](https://github.com/sebmarkbage)) -* Add `useSyncExternalStore` to help external store libraries integrate with React. ([#15022](https://github.com/facebook/react/pull/15022), [#18000](https://github.com/facebook/react/pull/18000), [#18771](https://github.com/facebook/react/pull/18771), [#22211](https://github.com/facebook/react/pull/22211), [#22292](https://github.com/facebook/react/pull/22292), [#22239](https://github.com/facebook/react/pull/22239), [#22347](https://github.com/facebook/react/pull/22347), [#23150](https://github.com/facebook/react/pull/23150) by [@acdlite](https://github.com/acdlite), [@bvaughn](https://github.com/bvaughn), and [@drarmstr](https://github.com/drarmstr)) -* Add `startTransition` as a version of `useTransition` without pending feedback. ([#19696](https://github.com/facebook/react/pull/19696) by [@rickhanlonii](https://github.com/rickhanlonii)) -* Add `useInsertionEffect` for CSS-in-JS libraries. ([#21913](https://github.com/facebook/react/pull/21913) by [@rickhanlonii](https://github.com/rickhanlonii)) -* Make Suspense remount layout effects when content reappears. ([#19322](https://github.com/facebook/react/pull/19322), [#19374](https://github.com/facebook/react/pull/19374), [#19523](https://github.com/facebook/react/pull/19523), [#20625](https://github.com/facebook/react/pull/20625), [#21079](https://github.com/facebook/react/pull/21079) by [@acdlite](https://github.com/acdlite), [@bvaughn](https://github.com/bvaughn), and [@lunaruan](https://github.com/lunaruan)) -* Make `` re-run effects to check for restorable state. ([#19523](https://github.com/facebook/react/pull/19523) , [#21418](https://github.com/facebook/react/pull/21418) by [@bvaughn](https://github.com/bvaughn) and [@lunaruan](https://github.com/lunaruan)) -* Assume Symbols are always available. ([#23348](https://github.com/facebook/react/pull/23348) by [@sebmarkbage](https://github.com/sebmarkbage)) -* Remove `object-assign` polyfill. ([#23351](https://github.com/facebook/react/pull/23351) by [@sebmarkbage](https://github.com/sebmarkbage)) -* Remove unsupported `unstable_changedBits` API. ([#20953](https://github.com/facebook/react/pull/20953) by [@acdlite](https://github.com/acdlite)) -* Allow components to render undefined. ([#21869](https://github.com/facebook/react/pull/21869) by [@rickhanlonii](https://github.com/rickhanlonii)) -* Flush `useEffect` resulting from discrete events like clicks synchronously. ([#21150](https://github.com/facebook/react/pull/21150) by [@acdlite](https://github.com/acdlite)) -* Suspense `fallback={undefined}` now behaves the same as `null` and isn't ignored. ([#21854](https://github.com/facebook/react/pull/21854) by [@rickhanlonii](https://github.com/rickhanlonii)) -* Consider all `lazy()` resolving to the same component equivalent. ([#20357](https://github.com/facebook/react/pull/20357) by [@sebmarkbage](https://github.com/sebmarkbage)) -* Don't patch console during first render. ([#22308](https://github.com/facebook/react/pull/22308) by [@lunaruan](https://github.com/lunaruan)) -* Improve memory usage. ([#21039](https://github.com/facebook/react/pull/21039) by [@bgirard](https://github.com/bgirard)) -* Improve messages if string coercion throws (Temporal.*, Symbol, etc.) ([#22064](https://github.com/facebook/react/pull/22064) by [@justingrant](https://github.com/justingrant)) -* Use `setImmediate` when available over `MessageChannel`. ([#20834](https://github.com/facebook/react/pull/20834) by [@gaearon](https://github.com/gaearon)) -* Fix context failing to propagate inside suspended trees. ([#23095](https://github.com/facebook/react/pull/23095) by [@gaearon](https://github.com/gaearon)) -* Fix `useReducer` observing incorrect props by removing the eager bailout mechanism. ([#22445](https://github.com/facebook/react/pull/22445) by [@josephsavona](https://github.com/josephsavona)) -* Fix `setState` being ignored in Safari when appending iframes. ([#23111](https://github.com/facebook/react/pull/23111) by [@gaearon](https://github.com/gaearon)) -* Fix a crash when rendering `ZonedDateTime` in the tree. ([#20617](https://github.com/facebook/react/pull/20617) by [@dimaqq](https://github.com/dimaqq)) -* Fix a crash when document is set to `null` in tests. ([#22695](https://github.com/facebook/react/pull/22695) by [@SimenB](https://github.com/SimenB)) -* Fix `onLoad` not triggering when concurrent features are on. ([#23316](https://github.com/facebook/react/pull/23316) by [@gnoff](https://github.com/gnoff)) -* Fix a warning when a selector returns `NaN`. ([#23333](https://github.com/facebook/react/pull/23333) by [@hachibeeDI](https://github.com/hachibeeDI)) -* Fix a crash when document is set to `null` in tests. ([#22695](https://github.com/facebook/react/pull/22695) by [@SimenB](https://github.com/SimenB)) -* Fix the generated license header. ([#23004](https://github.com/facebook/react/pull/23004) by [@vitaliemiron](https://github.com/vitaliemiron)) -* Add `package.json` as one of the entry points. ([#22954](https://github.com/facebook/react/pull/22954) by [@Jack](https://github.com/Jack-Works)) -* Allow suspending outside a Suspense boundary. ([#23267](https://github.com/facebook/react/pull/23267) by [@acdlite](https://github.com/acdlite)) -* Log a recoverable error whenever hydration fails. ([#23319](https://github.com/facebook/react/pull/23319) by [@acdlite](https://github.com/acdlite)) +* Добавлены `useTransition` и `useDeferredValue` для разделения срочных обновлений и переходов. ([#10426](https://github.com/facebook/react/pull/10426), [#10715](https://github.com/facebook/react/pull/10715), [#15593](https://github.com/facebook/react/pull/15593), [#15272](https://github.com/facebook/react/pull/15272), [#15578](https://github.com/facebook/react/pull/15578), [#15769](https://github.com/facebook/react/pull/15769), [#17058](https://github.com/facebook/react/pull/17058), [#18796](https://github.com/facebook/react/pull/18796), [#19121](https://github.com/facebook/react/pull/19121), [#19703](https://github.com/facebook/react/pull/19703), [#19719](https://github.com/facebook/react/pull/19719), [#19724](https://github.com/facebook/react/pull/19724), [#20672](https://github.com/facebook/react/pull/20672), [#20976](https://github.com/facebook/react/pull/20976) от [@acdlite](https://github.com/acdlite), [@lunaruan](https://github.com/lunaruan), [@rickhanlonii](https://github.com/rickhanlonii) и [@sebmarkbage](https://github.com/sebmarkbage)) +* Добавлен `useId` для генерации уникальных идентификаторов. ([#17322](https://github.com/facebook/react/pull/17322), [#18576](https://github.com/facebook/react/pull/18576), [#22644](https://github.com/facebook/react/pull/22644), [#22672](https://github.com/facebook/react/pull/22672), [#21260](https://github.com/facebook/react/pull/21260) от [@acdlite](https://github.com/acdlite), [@lunaruan](https://github.com/lunaruan) и [@sebmarkbage](https://github.com/sebmarkbage)) +* Добавлен `useSyncExternalStore` для помощи библиотекам внешних хранилищ в интеграции с React. ([#15022](https://github.com/facebook/react/pull/15022), [#18000](https://github.com/facebook/react/pull/18000), [#18771](https://github.com/facebook/react/pull/18771), [#22211](https://github.com/facebook/react/pull/22211), [#22292](https://github.com/facebook/react/pull/22292), [#22239](https://github.com/facebook/react/pull/22239), [#22347](https://github.com/facebook/react/pull/22347), [#23150](https://github.com/facebook/react/pull/23150) от [@acdlite](https://github.com/acdlite), [@bvaughn](https://github.com/bvaughn) и [@drarmstr](https://github.com/drarmstr)) +* Добавлена `startTransition` как версия `useTransition` без обратной связи о состоянии ожидания. ([#19696](https://github.com/facebook/react/pull/19696) от [@rickhanlonii](https://github.com/rickhanlonii)) +* Добавлен `useInsertionEffect` для библиотек CSS-in-JS. ([#21913](https://github.com/facebook/react/pull/21913) от [@rickhanlonii](https://github.com/rickhanlonii)) +* Suspense теперь повторно монтирует эффекты макета при повторном появлении контента. ([#19322](https://github.com/facebook/react/pull/19322), [#19374](https://github.com/facebook/react/pull/19374), [#19523](https://github.com/facebook/react/pull/19523), [#20625](https://github.com/facebook/react/pull/20625), [#21079](https://github.com/facebook/react/pull/21079) от [@acdlite](https://github.com/acdlite), [@bvaughn](https://github.com/bvaughn) и [@lunaruan](https://github.com/lunaruan)) +* `` теперь повторно запускает эффекты для проверки восстанавливаемого состояния. ([#19523](https://github.com/facebook/react/pull/19523), [#21418](https://github.com/facebook/react/pull/21418) от [@bvaughn](https://github.com/bvaughn) и [@lunaruan](https://github.com/lunaruan)) +* Предполагается, что Symbols всегда доступны. ([#23348](https://github.com/facebook/react/pull/23348) от [@sebmarkbage](https://github.com/sebmarkbage)) +* Удален полифилл `object-assign`. ([#23351](https://github.com/facebook/react/pull/23351) от [@sebmarkbage](https://github.com/sebmarkbage)) +* Удален неподдерживаемый API `unstable_changedBits`. ([#20953](https://github.com/facebook/react/pull/20953) от [@acdlite](https://github.com/acdlite)) +* Компоненты теперь могут рендерить `undefined`. ([#21869](https://github.com/facebook/react/pull/21869) от [@rickhanlonii](https://github.com/rickhanlonii)) +* Эффекты, вызванные дискретными событиями, такими как клики, теперь синхронно применяются. ([#21150](https://github.com/facebook/react/pull/21150) от [@acdlite](https://github.com/acdlite)) +* `fallback={undefined}` в Suspense теперь ведет себя так же, как `null`, и не игнорируется. ([#21854](https://github.com/facebook/react/pull/21854) от [@rickhanlonii](https://github.com/rickhanlonii)) +* Все `lazy()` теперь считаются эквивалентными одному и тому же компоненту. ([#20357](https://github.com/facebook/react/pull/20357) от [@sebmarkbage](https://github.com/sebmarkbage)) +* Консоль больше не перехватывается во время первого рендеринга. ([#22308](https://github.com/facebook/react/pull/22308) от [@lunaruan](https://github.com/lunaruan)) +* Улучшено использование памяти. ([#21039](https://github.com/facebook/react/pull/21039) от [@bgirard](https://github.com/bgirard)) +* Улучшены сообщения об ошибках при приведении строк (Temporal.*, Symbol и т. д.). ([#22064](https://github.com/facebook/react/pull/22064) от [@justingrant](https://github.com/justingrant)) +* Используется `setImmediate` вместо `MessageChannel`, если доступно. ([#20834](https://github.com/facebook/react/pull/20834) от [@gaearon](https://github.com/gaearon)) +* Исправлена ошибка, из-за которой контекст не передавался внутри подвешенных деревьев. ([#23095](https://github.com/facebook/react/pull/23095) от [@gaearon](https://github.com/gaearon)) +* Исправлена ошибка, из-за которой `useReducer` мог наблюдать некорректные пропсы, путем удаления механизма раннего выхода. ([#22445](https://github.com/facebook/react/pull/22445) от [@josephsavona](https://github.com/josephsavona)) +* Исправлена ошибка, из-за которой `setState` игнорировался в Safari при добавлении iframe. ([#23111](https://github.com/facebook/react/pull/23111) от [@gaearon](https://github.com/gaearon)) +* Исправлен сбой при рендеринге `ZonedDateTime` в дереве. ([#20617](https://github.com/facebook/react/pull/20617) от [@dimaqq](https://github.com/dimaqq)) +* Исправлен сбой при установке `document` в `null` в тестах. ([#22695](https://github.com/facebook/react/pull/22695) от [@SimenB](https://github.com/SimenB)) +* Исправлена ошибка, из-за которой `onLoad` не срабатывал при включенных конкурентных функциях. ([#23316](https://github.com/facebook/react/pull/23316) от [@gnoff](https://github.com/gnoff)) +* Исправлено предупреждение при возврате `NaN` селектором. ([#23333](https://github.com/facebook/react/pull/23333) от [@hachibeeDI](https://github.com/hachibeeDI)) +* Исправлен сбой при установке `document` в `null` в тестах. ([#22695](https://github.com/facebook/react/pull/22695) от [@SimenB](https://github.com/SimenB)) +* Исправлен сгенерированный заголовок лицензии. ([#23004](https://github.com/facebook/react/pull/23004) от [@vitaliemiron](https://github.com/vitaliemiron)) +* Добавлен `package.json` как одна из точек входа. ([#22954](https://github.com/facebook/react/pull/22954) от [@Jack](https://github.com/Jack-Works)) +* Разрешено приостанавливать выполнение вне границы Suspense. ([#23267](https://github.com/facebook/react/pull/23267) от [@acdlite](https://github.com/acdlite)) +* Регистрируется восстанавливаемая ошибка всякий раз, когда гидратация не удается. ([#23319](https://github.com/facebook/react/pull/23319) от [@acdlite](https://github.com/acdlite)) ### React DOM {/*react-dom*/} -* Add `createRoot` and `hydrateRoot`. ([#10239](https://github.com/facebook/react/pull/10239), [#11225](https://github.com/facebook/react/pull/11225), [#12117](https://github.com/facebook/react/pull/12117), [#13732](https://github.com/facebook/react/pull/13732), [#15502](https://github.com/facebook/react/pull/15502), [#15532](https://github.com/facebook/react/pull/15532), [#17035](https://github.com/facebook/react/pull/17035), [#17165](https://github.com/facebook/react/pull/17165), [#20669](https://github.com/facebook/react/pull/20669), [#20748](https://github.com/facebook/react/pull/20748), [#20888](https://github.com/facebook/react/pull/20888), [#21072](https://github.com/facebook/react/pull/21072), [#21417](https://github.com/facebook/react/pull/21417), [#21652](https://github.com/facebook/react/pull/21652), [#21687](https://github.com/facebook/react/pull/21687), [#23207](https://github.com/facebook/react/pull/23207), [#23385](https://github.com/facebook/react/pull/23385) by [@acdlite](https://github.com/acdlite), [@bvaughn](https://github.com/bvaughn), [@gaearon](https://github.com/gaearon), [@lunaruan](https://github.com/lunaruan), [@rickhanlonii](https://github.com/rickhanlonii), [@trueadm](https://github.com/trueadm), and [@sebmarkbage](https://github.com/sebmarkbage)) -* Add selective hydration. ([#14717](https://github.com/facebook/react/pull/14717), [#14884](https://github.com/facebook/react/pull/14884), [#16725](https://github.com/facebook/react/pull/16725), [#16880](https://github.com/facebook/react/pull/16880), [#17004](https://github.com/facebook/react/pull/17004), [#22416](https://github.com/facebook/react/pull/22416), [#22629](https://github.com/facebook/react/pull/22629), [#22448](https://github.com/facebook/react/pull/22448), [#22856](https://github.com/facebook/react/pull/22856), [#23176](https://github.com/facebook/react/pull/23176) by [@acdlite](https://github.com/acdlite), [@gaearon](https://github.com/gaearon), [@salazarm](https://github.com/salazarm), and [@sebmarkbage](https://github.com/sebmarkbage)) -* Add `aria-description` to the list of known ARIA attributes. ([#22142](https://github.com/facebook/react/pull/22142) by [@mahyareb](https://github.com/mahyareb)) -* Add `onResize` event to video elements. ([#21973](https://github.com/facebook/react/pull/21973) by [@rileyjshaw](https://github.com/rileyjshaw)) -* Add `imageSizes` and `imageSrcSet` to known props. ([#22550](https://github.com/facebook/react/pull/22550) by [@eps1lon](https://github.com/eps1lon)) -* Allow non-string `