From 0636a1d84b16beb004efea2f36772662d1a60ba7 Mon Sep 17 00:00:00 2001
From: "translate-react-bot[bot]"
<251169733+translate-react-bot[bot]@users.noreply.github.com>
Date: Tue, 2 Jun 2026 14:15:47 +0000
Subject: [PATCH] =?UTF-8?q?docs:=20translate=20`react-19-upgrade-guide.md`?=
=?UTF-8?q?=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../blog/2024/04/25/react-19-upgrade-guide.md | 395 +++++++++---------
1 file changed, 197 insertions(+), 198 deletions(-)
diff --git a/src/content/blog/2024/04/25/react-19-upgrade-guide.md b/src/content/blog/2024/04/25/react-19-upgrade-guide.md
index cb83a61764..55947639e8 100644
--- a/src/content/blog/2024/04/25/react-19-upgrade-guide.md
+++ b/src/content/blog/2024/04/25/react-19-upgrade-guide.md
@@ -2,139 +2,139 @@
title: "React 19 Upgrade Guide"
author: Ricky Hanlon
date: 2024/04/25
-description: The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading apps and libraries to React 19.
+description: Улучшения, добавленные в React 19, требуют некоторых критических изменений, но мы постарались сделать обновление максимально плавным и не ожидаем, что эти изменения затронут большинство приложений. В этой статье мы проведем вас через шаги по обновлению приложений и библиотек до React 19.
---
-April 25, 2024 by [Ricky Hanlon](https://twitter.com/rickhanlonii)
+25 апреля 2024 г. от [Ricky Hanlon](https://twitter.com/rickhanlonii)
---
-The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible, and we don't expect the changes to impact most apps.
+Улучшения, добавленные в React 19, требуют некоторых изменений, нарушающих обратную совместимость, но мы постарались сделать обновление максимально плавным, и не ожидаем, что эти изменения повлияют на большинство приложений.
-#### React 18.3 has also been published {/*react-18-3*/}
+#### Также опубликован React 18.3 {/*react-18-3*/}
-To help make the upgrade to React 19 easier, we've published a `react@18.3` release that is identical to 18.2 but adds warnings for deprecated APIs and other changes that are needed for React 19.
+Чтобы облегчить переход на React 19, мы опубликовали релиз `react@18.3`, который идентичен 18.2, но добавляет предупреждения об устаревших API и других изменениях, необходимых для React 19.
-We recommend upgrading to React 18.3 first to help identify any issues before upgrading to React 19.
+Мы рекомендуем сначала обновиться до React 18.3, чтобы выявить возможные проблемы перед обновлением до React 19.
-For a list of changes in 18.3 see the [Release Notes](https://github.com/facebook/react/blob/main/CHANGELOG.md#1830-april-25-2024).
+Список изменений в 18.3 см. в [Заметках к релизу](https://github.com/facebook/react/blob/main/CHANGELOG.md#1830-april-25-2024).
-In this post, we will guide you through the steps for upgrading to React 19:
+В этой статье мы проведем вас через шаги по обновлению до React 19:
-- [Installing](#installing)
+- [Установка](#installing)
- [Codemods](#codemods)
-- [Breaking changes](#breaking-changes)
-- [New deprecations](#new-deprecations)
-- [Notable changes](#notable-changes)
-- [TypeScript changes](#typescript-changes)
+- [Изменения, нарушающие обратную совместимость](#breaking-changes)
+- [Новые устаревшие функции](#new-deprecations)
+- [Заметные изменения](#notable-changes)
+- [Изменения TypeScript](#typescript-changes)
- [Changelog](#changelog)
-If you'd like to help us test React 19, follow the steps in this upgrade guide and [report any issues](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) you encounter. For a list of new features added to React 19, see the [React 19 release post](/blog/2024/12/05/react-19).
+Если вы хотите помочь нам протестировать React 19, следуйте инструкциям в этом руководстве по обновлению и [сообщайте о любых проблемах](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D), с которыми вы столкнетесь. Список новых функций, добавленных в React 19, см. в [посте о релизе React 19](/blog/2024/12/05/react-19).
---
-## Installing {/*installing*/}
+## Установка {/*installing*/}
-#### New JSX Transform is now required {/*new-jsx-transform-is-now-required*/}
+#### Новый JSX-трансформатор теперь обязателен {/*new-jsx-transform-is-now-required*/}
-We introduced a [new JSX transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) in 2020 to improve bundle size and use JSX without importing React. In React 19, we're adding additional improvements like using ref as a prop and JSX speed improvements that require the new transform.
+Мы представили [новый JSX-трансформатор](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) в 2020 году для улучшения размера сборки и использования JSX без импорта React. В React 19 мы добавляем дополнительные улучшения, такие как использование `ref` в качестве пропса и улучшения скорости JSX, которые требуют нового трансформатора.
-If the new transform is not enabled, you will see this warning:
+Если новый трансформатор не включен, вы увидите это предупреждение:
-Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform
+Ваше приложение (или одна из его зависимостей) использует устаревший JSX-трансформатор. Обновитесь до современного JSX-трансформатора для повышения производительности: https://react.dev/link/new-jsx-transform
-We expect most apps will not be affected since the transform is enabled in most environments already. For manual instructions on how to upgrade, please see the [announcement post](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html).
+Мы ожидаем, что большинство приложений не пострадают, так как трансформатор уже включен в большинстве сред. Инструкции по обновлению вручную см. в [анонсе](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html).
-To install the latest version of React and React DOM:
+Чтобы установить последнюю версию React и React DOM:
```bash
npm install --save-exact react@^19.0.0 react-dom@^19.0.0
```
-Or, if you're using Yarn:
+Или, если вы используете Yarn:
```bash
yarn add --exact react@^19.0.0 react-dom@^19.0.0
```
-If you're using TypeScript, you also need to update the types.
+Если вы используете TypeScript, вам также необходимо обновить типы.
```bash
npm install --save-exact @types/react@^19.0.0 @types/react-dom@^19.0.0
```
-Or, if you're using Yarn:
+Или, если вы используете Yarn:
```bash
yarn add --exact @types/react@^19.0.0 @types/react-dom@^19.0.0
```
-We're also including a codemod for the most common replacements. See [TypeScript changes](#typescript-changes) below.
+Мы также включаем codemod для наиболее распространенных замен. См. [Изменения TypeScript](#typescript-changes) ниже.
## Codemods {/*codemods*/}
-To help with the upgrade, we've worked with the team at [codemod.com](https://codemod.com) to publish codemods that will automatically update your code to many of the new APIs and patterns in React 19.
+Чтобы помочь с обновлением, мы сотрудничали с командой [codemod.com](https://codemod.com) для публикации codemods, которые автоматически обновят ваш код до многих новых API и паттернов в React 19.
-All codemods are available in the [`react-codemod` repo](https://github.com/reactjs/react-codemod) and the Codemod team have joined in helping maintain the codemods. To run these codemods, we recommend using the `codemod` command instead of the `react-codemod` because it runs faster, handles more complex code migrations, and provides better support for TypeScript.
+Все codemods доступны в репозитории [`react-codemod`](https://github.com/reactjs/react-codemod), и команда Codemod присоединилась к поддержке codemods. Для запуска этих codemods мы рекомендуем использовать команду `codemod` вместо `react-codemod`, поскольку она работает быстрее, обрабатывает более сложные миграции кода и обеспечивает лучшую поддержку TypeScript.
-#### Run all React 19 codemods {/*run-all-react-19-codemods*/}
+#### Запуск всех codemods React 19 {/*run-all-react-19-codemods*/}
-Run all codemods listed in this guide with the React 19 `codemod` recipe:
+Запустите все codemods, перечисленные в этом руководстве, с помощью рецепта `codemod` для React 19:
```bash
npx codemod@latest react/19/migration-recipe
```
-This will run the following codemods from `react-codemod`:
-- [`replace-reactdom-render`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-reactdom-render)
+Это запустит следующие codemods из `react-codemod`:
+- [`replace-reactdom-render`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-reactdom-render)
- [`replace-string-ref`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-string-ref)
- [`replace-act-import`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-act-import)
-- [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-use-form-state)
+- [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-use-form-state)
- [`prop-types-typescript`](https://github.com/reactjs/react-codemod#react-proptypes-to-prop-types)
-This does not include the TypeScript changes. See [TypeScript changes](#typescript-changes) below.
+Это не включает изменения TypeScript. См. [Изменения TypeScript](#typescript-changes) ниже.
-Changes that include a codemod include the command below.
+Изменения, включающие codemod, сопровождаются командой ниже.
-For a list of all available codemods, see the [`react-codemod` repo](https://github.com/reactjs/react-codemod).
+Список всех доступных codemods см. в репозитории [`react-codemod`](https://github.com/reactjs/react-codemod).
-## Breaking changes {/*breaking-changes*/}
+## Изменения, нарушающие обратную совместимость {/*breaking-changes*/}
-### Errors in render are not re-thrown {/*errors-in-render-are-not-re-thrown*/}
+### Ошибки при рендеринге не перебрасываются {/*errors-in-render-are-not-re-thrown*/}
-In previous versions of React, errors thrown during render were caught and rethrown. In DEV, we would also log to `console.error`, resulting in duplicate error logs.
+В предыдущих версиях React ошибки, возникающие во время рендеринга, перехватывались и перебрасывались. В режиме разработки (DEV) мы также выводили сообщения в `console.error`, что приводило к дублированию логов ошибок.
-In React 19, we've [improved how errors are handled](/blog/2024/04/25/react-19#error-handling) to reduce duplication by not re-throwing:
+В React 19 мы [улучшили обработку ошибок](/blog/2024/04/25/react-19#error-handling), чтобы уменьшить дублирование, не перебрасывая их:
-- **Uncaught Errors**: Errors that are not caught by an Error Boundary are reported to `window.reportError`.
-- **Caught Errors**: Errors that are caught by an Error Boundary are reported to `console.error`.
+- **Неперехваченные ошибки**: Ошибки, которые не были перехвачены Error Boundary, сообщаются в `window.reportError`.
+- **Перехваченные ошибки**: Ошибки, которые были перехвачены Error Boundary, сообщаются в `console.error`.
-This change should not impact most apps, but if your production error reporting relies on errors being re-thrown, you may need to update your error handling. To support this, we've added new methods to `createRoot` and `hydrateRoot` for custom error handling:
+Это изменение не должно повлиять на большинство приложений, но если ваша система отчетности об ошибках в продакшене полагается на переброс ошибок, вам может потребоваться обновить обработку ошибок. Для поддержки этого мы добавили новые методы в `createRoot` и `hydrateRoot` для пользовательской обработки ошибок:
```js [[1, 2, "onUncaughtError"], [2, 5, "onCaughtError"]]
const root = createRoot(container, {
@@ -147,20 +147,20 @@ const root = createRoot(container, {
});
```
-For more info, see the docs for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot).
+Дополнительную информацию см. в документации по [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) и [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot).
-### Removed deprecated React APIs {/*removed-deprecated-react-apis*/}
+### Удалены устаревшие API React {/*removed-deprecated-react-apis*/}
-#### Removed: `propTypes` and `defaultProps` for functions {/*removed-proptypes-and-defaultprops*/}
-`PropTypes` were deprecated in [April 2017 (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings).
+#### Удалено: `propTypes` и `defaultProps` для функций {/*removed-proptypes-and-defaultprops*/}
+`PropTypes` были объявлены устаревшими в [апреле 2017 г. (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings).
-In React 19, we're removing the `propType` checks from the React package, and using them will be silently ignored. If you're using `propTypes`, we recommend migrating to TypeScript or another type-checking solution.
+В React 19 мы удаляем проверки `propTypes` из пакета React, и их использование будет молчаливо игнорироваться. Если вы используете `propTypes`, мы рекомендуем перейти на TypeScript или другое решение для проверки типов.
-We're also removing `defaultProps` from function components in place of ES6 default parameters. Class components will continue to support `defaultProps` since there is no ES6 alternative.
+Мы также удаляем `defaultProps` из функциональных компонентов в пользу параметров по умолчанию ES6. Классовые компоненты продолжат поддерживать `defaultProps`, поскольку для них нет альтернативы в ES6.
```js
-// Before
+// До
import PropTypes from 'prop-types';
function Heading({text}) {
@@ -174,7 +174,7 @@ Heading.defaultProps = {
};
```
```ts
-// After
+// После
interface Props {
text?: string;
}
@@ -185,7 +185,7 @@ function Heading({text = 'Hello, world!'}: Props) {
-Codemod `propTypes` to TypeScript with:
+Codemod `propTypes` в TypeScript с помощью:
```bash
npx codemod@latest react/prop-types-typescript
@@ -193,16 +193,16 @@ npx codemod@latest react/prop-types-typescript
-#### Removed: Legacy Context using `contextTypes` and `getChildContext` {/*removed-removing-legacy-context*/}
+#### Удалено: Устаревший контекст с использованием `contextTypes` и `getChildContext` {/*removed-removing-legacy-context*/}
-Legacy Context was deprecated in [October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html).
+Устаревший контекст был объявлен устаревшим в [октябре 2018 г. (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html).
-Legacy Context was only available in class components using the APIs `contextTypes` and `getChildContext`, and was replaced with `contextType` due to subtle bugs that were easy to miss. In React 19, we're removing Legacy Context to make React slightly smaller and faster.
+Устаревший контекст был доступен только в классовых компонентах с использованием API `contextTypes` и `getChildContext` и был заменен на `contextType` из-за тонких ошибок, которые было легко пропустить. В React 19 мы удаляем устаревший контекст, чтобы сделать React немного меньше и быстрее.
-If you're still using Legacy Context in class components, you'll need to migrate to the new `contextType` API:
+Если вы все еще используете устаревший контекст в классовых компонентах, вам нужно будет перейти на новый API `contextType`:
```js {5-11,19-21}
-// Before
+// До
import PropTypes from 'prop-types';
class Parent extends React.Component {
@@ -231,7 +231,7 @@ class Child extends React.Component {
```
```js {2,7,9,15}
-// After
+// После
const FooContext = React.createContext();
class Parent extends React.Component {
@@ -253,15 +253,15 @@ class Child extends React.Component {
}
```
-#### Removed: string refs {/*removed-string-refs*/}
-String refs were deprecated in [March, 2018 (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html).
+#### Удалено: строковые рефы {/*removed-string-refs*/}
+Строковые рефы были объявлены устаревшими в [марте 2018 г. (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html).
-Class components supported string refs before being replaced by ref callbacks due to [multiple downsides](https://github.com/facebook/react/issues/1373). In React 19, we're removing string refs to make React simpler and easier to understand.
+Классовые компоненты поддерживали строковые рефы до их замены на колбэки рефов из-за [множества недостатков](https://github.com/facebook/react/issues/1373). В React 19 мы удаляем строковые рефы, чтобы сделать React проще и понятнее.
-If you're still using string refs in class components, you'll need to migrate to ref callbacks:
+Если вы все еще используете строковые рефы в классовых компонентах, вам нужно будет перейти на колбэки рефов:
```js {4,8}
-// Before
+// До
class MyComponent extends React.Component {
componentDidMount() {
this.refs.input.focus();
@@ -274,7 +274,7 @@ class MyComponent extends React.Component {
```
```js {4,8}
-// After
+// После
class MyComponent extends React.Component {
componentDidMount() {
this.input.focus();
@@ -288,7 +288,7 @@ class MyComponent extends React.Component {
-Codemod string refs with `ref` callbacks:
+Codemod строковых рефов в колбэки рефов:
```bash
npx codemod@latest react/19/replace-string-ref
@@ -296,45 +296,45 @@ npx codemod@latest react/19/replace-string-ref
-#### Removed: Module pattern factories {/*removed-module-pattern-factories*/}
-Module pattern factories were deprecated in [August 2019 (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-module-pattern-factories).
+#### Удалено: фабрики шаблонных модулей {/*removed-module-pattern-factories*/}
+Фабрики шаблонных модулей были объявлены устаревшими в [августе 2019 г. (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-module-pattern-factories).
-This pattern was rarely used and supporting it causes React to be slightly larger and slower than necessary. In React 19, we're removing support for module pattern factories, and you'll need to migrate to regular functions:
+Этот паттерн использовался редко, и его поддержка делает React немного больше и медленнее, чем необходимо. В React 19 мы удаляем поддержку фабрик шаблонных модулей, и вам нужно будет перейти на обычные функции:
```js
-// Before
+// До
function FactoryComponent() {
return { render() { return
; } }
}
```
```js
-// After
+// После
function FactoryComponent() {
return ;
}
```
-#### Removed: `React.createFactory` {/*removed-createfactory*/}
-`createFactory` was deprecated in [February 2020 (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#deprecating-createfactory).
+#### Удалено: `React.createFactory` {/*removed-createfactory*/}
+`createFactory` был объявлен устаревшим в [феврале 2020 г. (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#deprecating-createfactory).
-Using `createFactory` was common before broad support for JSX, but it's rarely used today and can be replaced with JSX. In React 19, we're removing `createFactory` and you'll need to migrate to JSX:
+Использование `createFactory` было обычным делом до широкой поддержки JSX, но сегодня оно используется редко и может быть заменено JSX. В React 19 мы удаляем `createFactory`, и вам нужно будет перейти на JSX:
```js
-// Before
+// До
import { createFactory } from 'react';
const button = createFactory('button');
```
```js
-// After
+// После
const button = ;
```
-#### Removed: `react-test-renderer/shallow` {/*removed-react-test-renderer-shallow*/}
+#### Удалено: `react-test-renderer/shallow` {/*removed-react-test-renderer-shallow*/}
-In React 18, we updated `react-test-renderer/shallow` to re-export [react-shallow-renderer](https://github.com/enzymejs/react-shallow-renderer). In React 19, we're removing `react-test-render/shallow` to prefer installing the package directly:
+В React 18 мы обновили `react-test-renderer/shallow` для повторного экспорта [react-shallow-renderer](https://github.com/enzymejs/react-shallow-renderer). В React 19 мы удаляем `react-test-render/shallow`, чтобы предпочесть прямую установку пакета:
```bash
npm install react-shallow-renderer --save-dev
@@ -346,42 +346,42 @@ npm install react-shallow-renderer --save-dev
-##### Please reconsider shallow rendering {/*please-reconsider-shallow-rendering*/}
+##### Пожалуйста, пересмотрите поверхностное рендерирование {/*please-reconsider-shallow-rendering*/}
-Shallow rendering depends on React internals and can block you from future upgrades. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro).
+Поверхностное рендерирование зависит от внутренних механизмов React и может блокировать вас от будущих обновлений. Мы рекомендуем перенести ваши тесты на [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) или [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro).
-### Removed deprecated React DOM APIs {/*removed-deprecated-react-dom-apis*/}
+### Удалены устаревшие API React DOM {/*removed-deprecated-react-dom-apis*/}
-#### Removed: `react-dom/test-utils` {/*removed-react-dom-test-utils*/}
+#### Удалено: `react-dom/test-utils` {/*removed-react-dom-test-utils*/}
-We've moved `act` from `react-dom/test-utils` to the `react` package:
+Мы переместили `act` из `react-dom/test-utils` в пакет `react`:
-`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. Import `act` from `react` instead of `react-dom/test-utils`. See https://react.dev/warnings/react-dom-test-utils for more info.
+`ReactDOMTestUtils.act` устарел в пользу `React.act`. Импортируйте `act` из `react`, а не из `react-dom/test-utils`. См. https://react.dev/warnings/react-dom-test-utils для получения дополнительной информации.
-To fix this warning, you can import `act` from `react`:
+Чтобы исправить это предупреждение, вы можете импортировать `act` из `react`:
```diff
- import {act} from 'react-dom/test-utils'
+ import {act} from 'react';
```
-All other `test-utils` functions have been removed. These utilities were uncommon, and made it too easy to depend on low level implementation details of your components and React. In React 19, these functions will error when called and their exports will be removed in a future version.
+Все остальные функции `test-utils` были удалены. Эти утилиты использовались редко и слишком упрощали зависимость от низкоуровневых деталей реализации ваших компонентов и React. В React 19 эти функции будут вызывать ошибку при вызове, а их экспорты будут удалены в будущей версии.
-See the [warning page](https://react.dev/warnings/react-dom-test-utils) for alternatives.
+См. [страницу предупреждений](https://react.dev/warnings/react-dom-test-utils) для альтернатив.
-Codemod `ReactDOMTestUtils.act` to `React.act`:
+Codemod `ReactDOMTestUtils.act` в `React.act`:
```bash
npx codemod@latest react/19/replace-act-import
@@ -389,16 +389,16 @@ npx codemod@latest react/19/replace-act-import
-#### Removed: `ReactDOM.render` {/*removed-reactdom-render*/}
+#### Удалено: `ReactDOM.render` {/*removed-reactdom-render*/}
-`ReactDOM.render` was deprecated in [March 2022 (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). In React 19, we're removing `ReactDOM.render` and you'll need to migrate to using [`ReactDOM.createRoot`](https://react.dev/reference/react-dom/client/createRoot):
+`ReactDOM.render` был объявлен устаревшим в [марте 2022 г. (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). В React 19 мы удаляем `ReactDOM.render`, и вам нужно будет перейти на использование [`ReactDOM.createRoot`](https://react.dev/reference/react-dom/client/createRoot):
```js
-// Before
+// До
import {render} from 'react-dom';
render(, document.getElementById('root'));
-// After
+// После
import {createRoot} from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render();
@@ -406,7 +406,7 @@ root.render();
-Codemod `ReactDOM.render` to `ReactDOMClient.createRoot`:
+Codemod `ReactDOM.render` в `ReactDOMClient.createRoot`:
```bash
npx codemod@latest react/19/replace-reactdom-render
@@ -414,23 +414,23 @@ npx codemod@latest react/19/replace-reactdom-render
-#### Removed: `ReactDOM.hydrate` {/*removed-reactdom-hydrate*/}
+#### Удалено: `ReactDOM.hydrate` {/*removed-reactdom-hydrate*/}
-`ReactDOM.hydrate` was deprecated in [March 2022 (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). In React 19, we're removing `ReactDOM.hydrate` you'll need to migrate to using [`ReactDOM.hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot),
+`ReactDOM.hydrate` был объявлен устаревшим в [марте 2022 г. (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). В React 19 мы удаляем `ReactDOM.hydrate`, и вам нужно будет перейти на использование [`ReactDOM.hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot),
```js
-// Before
+// До
import {hydrate} from 'react-dom';
hydrate(, document.getElementById('root'));
-// After
+// После
import {hydrateRoot} from 'react-dom/client';
hydrateRoot(document.getElementById('root'), );
```
-Codemod `ReactDOM.hydrate` to `ReactDOMClient.hydrateRoot`:
+Codemod `ReactDOM.hydrate` в `ReactDOMClient.hydrateRoot`:
```bash
npx codemod@latest react/19/replace-reactdom-render
@@ -438,24 +438,24 @@ npx codemod@latest react/19/replace-reactdom-render
-#### Removed: `unmountComponentAtNode` {/*removed-unmountcomponentatnode*/}
+#### Удалено: `unmountComponentAtNode` {/*removed-unmountcomponentatnode*/}
-`ReactDOM.unmountComponentAtNode` was deprecated in [March 2022 (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). In React 19, you'll need to migrate to using `root.unmount()`.
+`ReactDOM.unmountComponentAtNode` был объявлен устаревшим в [марте 2022 г. (v18.0.0)](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). В React 19 вам нужно будет перейти на использование `root.unmount()`.
```js
-// Before
+// До
unmountComponentAtNode(document.getElementById('root'));
-// After
+// После
root.unmount();
```
-For more see `root.unmount()` for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot#root-unmount) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot#root-unmount).
+Подробнее см. `root.unmount()` для [`createRoot`](https://react.dev/reference/react-dom/client/createRoot#root-unmount) и [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot#root-unmount).
-Codemod `unmountComponentAtNode` to `root.unmount`:
+Codemod `unmountComponentAtNode` в `root.unmount`:
```bash
npx codemod@latest react/19/replace-reactdom-render
@@ -463,14 +463,14 @@ npx codemod@latest react/19/replace-reactdom-render
-#### Removed: `ReactDOM.findDOMNode` {/*removed-reactdom-finddomnode*/}
+#### Удалено: `ReactDOM.findDOMNode` {/*removed-reactdom-finddomnode*/}
-`ReactDOM.findDOMNode` was [deprecated in October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html#deprecations-in-strictmode).
+`ReactDOM.findDOMNode` был [объявлен устаревшим в октябре 2018 г. (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html#deprecations-in-strictmode).
-We're removing `findDOMNode` because it was a legacy escape hatch that was slow to execute, fragile to refactoring, only returned the first child, and broke abstraction levels (see more [here](https://legacy.reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage)). You can replace `ReactDOM.findDOMNode` with [DOM refs](/learn/manipulating-the-dom-with-refs):
+Мы удаляем `findDOMNode`, поскольку это был устаревший обходной путь, который медленно выполнялся, был хрупким к рефакторингу, возвращал только первый дочерний элемент и нарушал уровни абстракции (подробнее см. [здесь](https://legacy.reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage)). Вы можете заменить `ReactDOM.findDOMNode` на [DOM-рефы](/learn/manipulating-the-dom-with-refs):
```js
-// Before
+// До
import {findDOMNode} from 'react-dom';
function AutoselectingInput() {
@@ -484,7 +484,7 @@ function AutoselectingInput() {
```
```js
-// After
+// После
function AutoselectingInput() {
const ref = useRef(null);
useEffect(() => {
@@ -495,65 +495,65 @@ function AutoselectingInput() {
}
```
-## New deprecations {/*new-deprecations*/}
+## Новые устаревшие функции {/*new-deprecations*/}
-### Deprecated: `element.ref` {/*deprecated-element-ref*/}
+### Устарело: `element.ref` {/*deprecated-element-ref*/}
-React 19 supports [`ref` as a prop](/blog/2024/04/25/react-19#ref-as-a-prop), so we're deprecating the `element.ref` in place of `element.props.ref`.
+React 19 поддерживает [`ref` как пропс](/blog/2024/04/25/react-19#ref-as-a-prop), поэтому мы объявляем устаревшим `element.ref` в пользу `element.props.ref`.
-Accessing `element.ref` will warn:
+Доступ к `element.ref` вызовет предупреждение:
-Accessing element.ref is no longer supported. ref is now a regular prop. It will be removed from the JSX Element type in a future release.
+Доступ к element.ref больше не поддерживается. ref теперь является обычным пропсом. Он будет удален из типа JSX Element в будущей версии.
-### Deprecated: `react-test-renderer` {/*deprecated-react-test-renderer*/}
+### Устарело: `react-test-renderer` {/*deprecated-react-test-renderer*/}
-We are deprecating `react-test-renderer` because it implements its own renderer environment that doesn't match the environment users use, promotes testing implementation details, and relies on introspection of React's internals.
+Мы объявляем устаревшим `react-test-renderer`, поскольку он реализует собственную среду рендеринга, которая не соответствует среде, используемой пользователями, способствует тестированию деталей реализации и полагается на интроспекцию внутренних механизмов React.
-The test renderer was created before there were more viable testing strategies available like [React Testing Library](https://testing-library.com), and we now recommend using a modern testing library instead.
+Тестовый рендерер был создан до появления более жизнеспособных стратегий тестирования, таких как [React Testing Library](https://testing-library.com), и теперь мы рекомендуем использовать современную библиотеку тестирования вместо него.
-In React 19, `react-test-renderer` logs a deprecation warning, and has switched to concurrent rendering. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro) for a modern and well supported testing experience.
+В React 19 `react-test-renderer` выводит предупреждение об устаревании и переключился на конкурентный рендеринг. Мы рекомендуем перенести ваши тесты на [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) или [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro/) для современного и хорошо поддерживаемого опыта тестирования.
-## Notable changes {/*notable-changes*/}
+## Заметные изменения {/*notable-changes*/}
-### StrictMode changes {/*strict-mode-improvements*/}
+### Изменения StrictMode {/*strict-mode-improvements*/}
-React 19 includes several fixes and improvements to Strict Mode.
+React 19 включает несколько исправлений и улучшений для Strict Mode.
-When double rendering in Strict Mode in development, `useMemo` and `useCallback` will reuse the memoized results from the first render during the second render. Components that are already Strict Mode compatible should not notice a difference in behavior.
+При двойном рендеринге в Strict Mode в режиме разработки `useMemo` и `useCallback` будут повторно использовать мемоизированные результаты первого рендеринга во время второго рендеринга. Компоненты, которые уже совместимы со Strict Mode, не должны заметить разницы в поведении.
-As with all Strict Mode behaviors, these features are designed to proactively surface bugs in your components during development so you can fix them before they are shipped to production. For example, during development, Strict Mode will double-invoke ref callback functions on initial mount, to simulate what happens when a mounted component is replaced by a Suspense fallback.
+Как и все функции Strict Mode, эти функции предназначены для проактивного выявления ошибок в ваших компонентах во время разработки, чтобы вы могли исправить их до того, как они будут выпущены в продакшен. Например, во время разработки Strict Mode будет дважды вызывать функции колбэков рефов при первоначальном монтировании, чтобы имитировать то, что происходит, когда смонтированный компонент заменяется запасным элементом Suspense.
-### Improvements to Suspense {/*improvements-to-suspense*/}
+### Улучшения Suspense {/*improvements-to-suspense*/}
-In React 19, when a component suspends, React will immediately commit the fallback of the nearest Suspense boundary without waiting for the entire sibling tree to render. After the fallback commits, React schedules another render for the suspended siblings to "pre-warm" lazy requests in the rest of the tree:
+В React 19, когда компонент приостанавливается (suspends), React немедленно зафиксирует запасной элемент ближайшего пограничного элемента Suspense, не дожидаясь рендеринга всего дерева братьев и сестер. После фиксации запасного элемента React планирует еще один рендеринг для приостановленных братьев и сестер, чтобы "предварительно разогреть" ленивые запросы в остальной части дерева:
-
+
-Previously, when a component suspended, the suspended siblings were rendered and then the fallback was committed.
+Ранее, когда компонент приостанавливался, рендерились братья и сестры, а затем фиксировался запасной элемент.
-
+
-In React 19, when a component suspends, the fallback is committed and then the suspended siblings are rendered.
+В React 19, когда компонент приостанавливается, фиксируется запасной элемент, а затем рендерится приостановленный братский элемент.
-This change means Suspense fallbacks display faster, while still warming lazy requests in the suspended tree.
+Это изменение означает, что запасные элементы Suspense отображаются быстрее, при этом "предварительно разогревая" ленивые запросы в приостановленном дереве.
-### UMD builds removed {/*umd-builds-removed*/}
+### Удалены UMD-сборки {/*umd-builds-removed*/}
-UMD was widely used in the past as a convenient way to load React without a build step. Now, there are modern alternatives for loading modules as scripts in HTML documents. Starting with React 19, React will no longer produce UMD builds to reduce the complexity of its testing and release process.
+UMD широко использовался в прошлом как удобный способ загрузки React без шага сборки. Теперь существуют современные альтернативы для загрузки модулей в виде скриптов в HTML-документах. Начиная с React 19, React больше не будет создавать UMD-сборки, чтобы уменьшить сложность процесса тестирования и выпуска.
-To load React 19 with a script tag, we recommend using an ESM-based CDN such as [esm.sh](https://esm.sh/).
+Чтобы загрузить React 19 с помощью тега скрипта, мы рекомендуем использовать CDN на основе ESM, такой как [esm.sh](https://esm.sh/).
```html
```
-### Libraries depending on React internals may block upgrades {/*libraries-depending-on-react-internals-may-block-upgrades*/}
+### Библиотеки, зависящие от внутренних механизмов React, могут блокировать обновления {/*libraries-depending-on-react-internals-may-block-upgrades*/}
-This release includes changes to React internals that may impact libraries that ignore our pleas to not use internals like `SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED`. These changes are necessary to land improvements in React 19, and will not break libraries that follow our guidelines.
+Этот релиз включает изменения во внутренних механизмах React, которые могут повлиять на библиотеки, игнорирующие наши просьбы не использовать внутренние механизмы, такие как `SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED`. Эти изменения необходимы для внедрения улучшений в React 19 и не нарушат работу библиотек, которые следуют нашим рекомендациям.
-Based on our [Versioning Policy](https://react.dev/community/versioning-policy#what-counts-as-a-breaking-change), these updates are not listed as breaking changes, and we are not including docs for how to upgrade them. The recommendation is to remove any code that depends on internals.
+В соответствии с нашей [Политикой версионирования](https://react.dev/community/versioning-policy#what-counts-as-a-breaking-change), эти обновления не перечислены как нарушающие обратную совместимость, и мы не предоставляем документацию по их обновлению. Рекомендация — удалить любой код, который зависит от внутренних механизмов.
-To reflect the impact of using internals, we have renamed the `SECRET_INTERNALS` suffix to:
+Чтобы отразить влияние использования внутренних механизмов, мы переименовали суффикс `SECRET_INTERNALS` в:
`_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE`
-In the future we will more aggressively block accessing internals from React to discourage usage and ensure users are not blocked from upgrading.
+В будущем мы будем более агрессивно блокировать доступ к внутренним механизмам React, чтобы препятствовать их использованию и гарантировать, что пользователи не будут заблокированы от обновления.
-## TypeScript changes {/*typescript-changes*/}
+## Изменения в TypeScript {/*typescript-changes*/}
-### Removed deprecated TypeScript types {/*removed-deprecated-typescript-types*/}
+### Удалены устаревшие типы TypeScript {/*removed-deprecated-typescript-types*/}
-We've cleaned up the TypeScript types based on the removed APIs in React 19. Some of the removed have types been moved to more relevant packages, and others are no longer needed to describe React's behavior.
+Мы очистили типы TypeScript на основе удалённых API в React 19. Некоторые из удалённых типов были перемещены в более релевантные пакеты, а другие больше не нужны для описания поведения React.
-We've published [`types-react-codemod`](https://github.com/eps1lon/types-react-codemod/) to migrate most type related breaking changes:
+Мы опубликовали [`types-react-codemod`](https://github.com/eps1lon/types-react-codemod/), чтобы перенести большинство связанных с типами критических изменений:
```bash
npx types-react-codemod@latest preset-19 ./path-to-app
```
-If you have a lot of unsound access to `element.props`, you can run this additional codemod:
+Если у вас много некорректного доступа к `element.props`, вы можете запустить этот дополнительный codemod:
```bash
npx types-react-codemod@latest react-element-default-any-props ./path-to-your-react-ts-files
@@ -596,50 +596,49 @@ npx types-react-codemod@latest react-element-default-any-props ./path-to-your-re
-Check out [`types-react-codemod`](https://github.com/eps1lon/types-react-codemod/) for a list of supported replacements. If you feel a codemod is missing, it can be tracked in the [list of missing React 19 codemods](https://github.com/eps1lon/types-react-codemod/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22React+19%22+label%3Aenhancement).
+Ознакомьтесь с [`types-react-codemod`](https://github.com/eps1lon/types-react-codemod/) для получения списка поддерживаемых замен. Если вы считаете, что codemod отсутствует, его можно отследить в [списке отсутствующих codemods для React 19](https://github.com/eps1lon/types-react-codemod/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22React+19%22+label%3Aenhancement).
-### `ref` cleanups required {/*ref-cleanup-required*/}
+### Требуется очистка `ref` {/*ref-cleanup-required*/}
-_This change is included in the `react-19` codemod preset as [`no-implicit-ref-callback-return
-`](https://github.com/eps1lon/types-react-codemod/#no-implicit-ref-callback-return)._
+_Это изменение включено в пресет codemod `react-19` как [`no-implicit-ref-callback-return`](https://github.com/eps1lon/types-react-codemod/#no-implicit-ref-callback-return)._
-Due to the introduction of ref cleanup functions, returning anything else from a ref callback will now be rejected by TypeScript. The fix is usually to stop using implicit returns:
+Из-за введения функций очистки `ref` возврат чего-либо, кроме `undefined`, из колбэка `ref` теперь будет отклоняться TypeScript. Исправление обычно заключается в прекращении использования неявных возвратов:
```diff [[1, 1, "("], [1, 1, ")"], [2, 2, "{", 15], [2, 2, "}", 1]]
-
(instance = current)} />
+
{instance = current}} />
```
-The original code returned the instance of the `HTMLDivElement` and TypeScript wouldn't know if this was supposed to be a cleanup function or not.
+Исходный код возвращал экземпляр `HTMLDivElement`, и TypeScript не знал, предназначалась ли это функция очистки или нет.
-### `useRef` requires an argument {/*useref-requires-argument*/}
+### `useRef` требует аргумент {/*useref-requires-argument*/}
-_This change is included in the `react-19` codemod preset as [`refobject-defaults`](https://github.com/eps1lon/types-react-codemod/#refobject-defaults)._
+_Это изменение включено в пресет codemod `react-19` как [`refobject-defaults`](https://github.com/eps1lon/types-react-codemod/#refobject-defaults)._
-A long-time complaint of how TypeScript and React work has been `useRef`. We've changed the types so that `useRef` now requires an argument. This significantly simplifies its type signature. It'll now behave more like `createContext`.
+Долгое время жаловались на то, как TypeScript и React работают с `useRef`. Мы изменили типы так, что `useRef` теперь требует аргумент. Это значительно упрощает его сигнатуру типа. Теперь он будет вести себя больше как `createContext`.
```ts
-// @ts-expect-error: Expected 1 argument but saw none
+// @ts-expect-error: Ожидался 1 аргумент, но не было предоставлено
useRef();
-// Passes
+// Проходит
useRef(undefined);
-// @ts-expect-error: Expected 1 argument but saw none
+// @ts-expect-error: Ожидался 1 аргумент, но не было предоставлено
createContext();
-// Passes
+// Проходит
createContext(undefined);
```
-This now also means that all refs are mutable. You'll no longer hit the issue where you can't mutate a ref because you initialised it with `null`:
+Теперь это также означает, что все `ref` являются изменяемыми. Вы больше не столкнётесь с проблемой, когда не можете изменить `ref`, потому что инициализировали его с помощью `null`:
```ts
const ref = useRef(null);
-// Cannot assign to 'current' because it is a read-only property
+// Нельзя присвоить значение 'current', потому что это свойство только для чтения
ref.current = 1;
```
-`MutableRef` is now deprecated in favor of a single `RefObject` type which `useRef` will always return:
+`MutableRef` теперь устарел в пользу единого типа `RefObject`, который `useRef` всегда будет возвращать:
```ts
interface RefObject {
@@ -649,36 +648,36 @@ interface RefObject {
declare function useRef: RefObject
```
-`useRef` still has a convenience overload for `useRef(null)` that automatically returns `RefObject`. To ease migration due to the required argument for `useRef`, a convenience overload for `useRef(undefined)` was added that automatically returns `RefObject`.
+`useRef` по-прежнему имеет удобную перегрузку для `useRef(null)`, которая автоматически возвращает `RefObject`. Чтобы облегчить миграцию из-за обязательного аргумента для `useRef`, была добавлена удобная перегрузка для `useRef(undefined)`, которая автоматически возвращает `RefObject`.
-Check out [[RFC] Make all refs mutable](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/64772) for prior discussions about this change.
+Ознакомьтесь с [[RFC] Сделать все `ref` изменяемыми](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/64772) для предварительного обсуждения этого изменения.
-### Changes to the `ReactElement` TypeScript type {/*changes-to-the-reactelement-typescript-type*/}
+### Изменения в типе `ReactElement` TypeScript {/*changes-to-the-reactelement-typescript-type*/}
-_This change is included in the [`react-element-default-any-props`](https://github.com/eps1lon/types-react-codemod#react-element-default-any-props) codemod._
+_Это изменение включено в codemod [`react-element-default-any-props`](https://github.com/eps1lon/types-react-codemod#react-element-default-any-props)._
-The `props` of React elements now default to `unknown` instead of `any` if the element is typed as `ReactElement`. This does not affect you if you pass a type argument to `ReactElement`:
+`props` React-элементов теперь по умолчанию `unknown` вместо `any`, если элемент типизирован как `ReactElement`. Это не повлияет на вас, если вы передаёте аргумент типа в `ReactElement`:
```ts
type Example2 = ReactElement<{ id: string }>["props"];
// ^? { id: string }
```
-But if you relied on the default, you now have to handle `unknown`:
+Но если вы полагались на значение по умолчанию, теперь вам придётся обрабатывать `unknown`:
```ts
type Example = ReactElement["props"];
-// ^? Before, was 'any', now 'unknown'
+// ^? Раньше было 'any', теперь 'unknown'
```
-You should only need it if you have a lot of legacy code relying on unsound access of element props. Element introspection only exists as an escape hatch, and you should make it explicit that your props access is unsound via an explicit `any`.
+Вам это понадобится только в том случае, если у вас много устаревшего кода, полагающегося на некорректный доступ к пропсам элемента. Интроспекция элементов существует только как крайняя мера, и вы должны явно указывать, что ваш доступ к пропсам некорректен, с помощью явного `any`.
-### The JSX namespace in TypeScript {/*the-jsx-namespace-in-typescript*/}
-This change is included in the `react-19` codemod preset as [`scoped-jsx`](https://github.com/eps1lon/types-react-codemod#scoped-jsx)
+### Пространство имён JSX в TypeScript {/*the-jsx-namespace-in-typescript*/}
+Это изменение включено в пресет codemod `react-19` как [`scoped-jsx`](https://github.com/eps1lon/types-react-codemod#scoped-jsx)
-A long-time request is to remove the global `JSX` namespace from our types in favor of `React.JSX`. This helps prevent pollution of global types which prevents conflicts between different UI libraries that leverage JSX.
+Давний запрос — удалить глобальное пространство имён `JSX` из наших типов в пользу `React.JSX`. Это помогает предотвратить загрязнение глобальных типов, что предотвращает конфликты между различными библиотеками пользовательского интерфейса, использующими JSX.
-You'll now need to wrap module augmentation of the JSX namespace in `declare module "....":
+Теперь вам нужно будет обернуть дополнение модуля пространства имён JSX в `declare module "....":`
```diff
// global.d.ts
@@ -693,62 +692,62 @@ You'll now need to wrap module augmentation of the JSX namespace in `declare mod
+ }
```
-The exact module specifier depends on the JSX runtime you specified in the `compilerOptions` of your `tsconfig.json`:
+Точный спецификатор модуля зависит от JSX-рантайма, который вы указали в `compilerOptions` вашего `tsconfig.json`:
-- For `"jsx": "react-jsx"` it would be `react/jsx-runtime`.
-- For `"jsx": "react-jsxdev"` it would be `react/jsx-dev-runtime`.
-- For `"jsx": "react"` and `"jsx": "preserve"` it would be `react`.
+- Для `"jsx": "react-jsx"` это будет `react/jsx-runtime`.
+- Для `"jsx": "react-jsxdev"` это будет `react/jsx-dev-runtime`.
+- Для `"jsx": "react"` и `"jsx": "preserve"` это будет `react`.
-### Better `useReducer` typings {/*better-usereducer-typings*/}
+### Улучшенные типы `useReducer` {/*better-usereducer-typings*/}
-`useReducer` now has improved type inference thanks to [@mfp22](https://github.com/mfp22).
+`useReducer` теперь имеет улучшенное выведение типов благодаря [@mfp22](https://github.com/mfp22).
-However, this required a breaking change where `useReducer` doesn't accept the full reducer type as a type parameter but instead either needs none (and rely on contextual typing) or needs both the state and action type.
+Однако это потребовало критического изменения, при котором `useReducer` не принимает полный тип редьюсера в качестве параметра типа, а вместо этого либо не требует никакого (и полагается на контекстное типирование), либо требует как тип состояния, так и тип действия.
-The new best practice is _not_ to pass type arguments to `useReducer`.
+Новая лучшая практика — _не_ передавать аргументы типа в `useReducer`.
```diff
- useReducer>(reducer)
+ useReducer(reducer)
```
-This may not work in edge cases where you can explicitly type the state and action, by passing in the `Action` in a tuple:
+Это может не работать в крайних случаях, когда вы можете явно типизировать состояние и действие, передав `Action` в виде кортежа:
```diff
- useReducer>(reducer)
+ useReducer(reducer)
```
-If you define the reducer inline, we encourage to annotate the function parameters instead:
+Если вы определяете редьюсер встраиваемо, мы рекомендуем вместо этого аннотировать параметры функции:
```diff
- useReducer>((state, action) => state)
+ useReducer((state: State, action: Action) => state)
```
-This is also what you'd also have to do if you move the reducer outside of the `useReducer` call:
+Это также то, что вам придётся сделать, если вы вынесете редьюсер за пределы вызова `useReducer`:
```ts
const reducer = (state: State, action: Action) => state;
```
-## Changelog {/*changelog*/}
+## Список изменений {/*changelog*/}
-### Other breaking changes {/*other-breaking-changes*/}
+### Другие критические изменения {/*other-breaking-changes*/}
-- **react-dom**: Error for javascript URLs in `src` and `href` [#26507](https://github.com/facebook/react/pull/26507)
-- **react-dom**: Remove `errorInfo.digest` from `onRecoverableError` [#28222](https://github.com/facebook/react/pull/28222)
-- **react-dom**: Remove `unstable_flushControlled` [#26397](https://github.com/facebook/react/pull/26397)
-- **react-dom**: Remove `unstable_createEventHandle` [#28271](https://github.com/facebook/react/pull/28271)
-- **react-dom**: Remove `unstable_renderSubtreeIntoContainer` [#28271](https://github.com/facebook/react/pull/28271)
-- **react-dom**: Remove `unstable_runWithPriority` [#28271](https://github.com/facebook/react/pull/28271)
-- **react-is**: Remove deprecated methods from `react-is` [28224](https://github.com/facebook/react/pull/28224)
+- **react-dom**: Ошибка для javascript URL в `src` и `href` [#26507](https://github.com/facebook/react/pull/26507)
+- **react-dom**: Удалён `errorInfo.digest` из `onRecoverableError` [#28222](https://github.com/facebook/react/pull/28222)
+- **react-dom**: Удалён `unstable_flushControlled` [#26397](https://github.com/facebook/react/pull/26397)
+- **react-dom**: Удалён `unstable_createEventHandle` [#28271](https://github.com/facebook/react/pull/28271)
+- **react-dom**: Удалён `unstable_renderSubtreeIntoContainer` [#28271](https://github.com/facebook/react/pull/28271)
+- **react-dom**: Удалён `unstable_runWithPriority` [#28271](https://github.com/facebook/react/pull/28271)
+- **react-is**: Удалены устаревшие методы из `react-is` [28224](https://github.com/facebook/react/pull/28224)
-### Other notable changes {/*other-notable-changes*/}
+### Другие заметные изменения {/*other-notable-changes*/}
-- **react**: Batch sync, default and continuous lanes [#25700](https://github.com/facebook/react/pull/25700)
-- **react**: Don't prerender siblings of suspended component [#26380](https://github.com/facebook/react/pull/26380)
-- **react**: Detect infinite update loops caused by render phase updates [#26625](https://github.com/facebook/react/pull/26625)
-- **react-dom**: Transitions in popstate are now synchronous [#26025](https://github.com/facebook/react/pull/26025)
-- **react-dom**: Remove layout effect warning during SSR [#26395](https://github.com/facebook/react/pull/26395)
-- **react-dom**: Warn and don’t set empty string for src/href (except anchor tags) [#28124](https://github.com/facebook/react/pull/28124)
+- **react**: Пакетные, синхронные, стандартные и непрерывные очереди [#25700](https://github.com/facebook/react/pull/25700)
+- **react**: Не предрендерить соседей приостановленного компонента [#26380](https://github.com/facebook/react/pull/26380)
+- **react**: Обнаружение бесконечных циклов обновлений, вызванных обновлениями в фазе рендеринга [#26625](https://github.com/facebook/react/pull/26625)
+- **react-dom**: Переходы в popstate теперь синхронны [#26025](https://github.com/facebook/react/pull/26025)
+- **react-dom**: Удалено предупреждение о `layout effect` во время SSR [#26395](https://github.com/facebook/react/pull/26395)
+- **react-dom**: Предупреждение и не установка пустой строки для src/href (кроме тегов ``) [#28124](https://github.com/facebook/react/pull/28124)
-For a full list of changes, please see the [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md#1900-december-5-2024).
+Полный список изменений см. в [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md#1900-december-5-2024).
---
-Thanks to [Andrew Clark](https://twitter.com/acdlite), [Eli White](https://twitter.com/Eli_White), [Jack Pope](https://github.com/jackpope), [Jan Kassens](https://github.com/kassens), [Josh Story](https://twitter.com/joshcstory), [Matt Carroll](https://twitter.com/mattcarrollcode), [Noah Lemen](https://twitter.com/noahlemen), [Sophie Alpert](https://twitter.com/sophiebits), and [Sebastian Silbermann](https://twitter.com/sebsilbermann) for reviewing and editing this post.
+Благодарим [Andrew Clark](https://twitter.com/acdlite), [Eli White](https://twitter.com/Eli_White), [Jack Pope](https://github.com/jackpope), [Jan Kassens](https://github.com/kassens), [Josh Story](https://twitter.com/joshcstory), [Matt Carroll](https://twitter.com/mattcarrollcode), [Noah Lemen](https://twitter.com/noahlemen), [Sophie Alpert](https://twitter.com/sophiebits) и [Sebastian Silbermann](https://twitter.com/sebsilbermann) за рецензирование и редактирование этой публикации.
\ No newline at end of file