diff --git a/src/content/reference/rules/index.md b/src/content/reference/rules/index.md index dd5f7456c8..538f227a9a 100644 --- a/src/content/reference/rules/index.md +++ b/src/content/reference/rules/index.md @@ -3,7 +3,7 @@ title: Rules of React --- -Just as different programming languages have their own ways of expressing concepts, React has its own idioms — or rules — for how to express patterns in a way that is easy to understand and yields high-quality applications. +Подобно тому, как разные языки программирования имеют свои способы выражения концепций, React имеет свои идиомы — или правила — для выражения паттернов таким образом, чтобы это было легко понять и приводило к высококачественным приложениям. @@ -11,42 +11,41 @@ Just as different programming languages have their own ways of expressing concep --- -To learn more about expressing UIs with React, we recommend reading [Thinking in React](/learn/thinking-in-react). +Чтобы узнать больше о выражении пользовательских интерфейсов с помощью React, мы рекомендуем прочитать [Мышление в стиле React](/learn/thinking-in-react). -This section describes the rules you need to follow to write idiomatic React code. Writing idiomatic React code can help you write well organized, safe, and composable applications. These properties make your app more resilient to changes and makes it easier to work with other developers, libraries, and tools. +Этот раздел описывает правила, которым вы должны следовать, чтобы писать идиоматичный код React. Написание идиоматичного кода React может помочь вам создавать хорошо организованные, безопасные и компонуемые приложения. Эти свойства делают ваше приложение более устойчивым к изменениям и облегчают работу с другими разработчиками, библиотеками и инструментами. -These rules are known as the **Rules of React**. They are rules – and not just guidelines – in the sense that if they are broken, your app likely has bugs. Your code also becomes unidiomatic and harder to understand and reason about. +Эти правила известны как **Правила React**. Они являются правилами, а не просто рекомендациями, в том смысле, что если они нарушены, ваше приложение, вероятно, содержит ошибки. Ваш код также становится неидиоматичным и его труднее понять и осмыслить. -We strongly recommend using [Strict Mode](/reference/react/StrictMode) alongside React's [ESLint plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to help your codebase follow the Rules of React. By following the Rules of React, you'll be able to find and address these bugs and keep your application maintainable. +Мы настоятельно рекомендуем использовать [Strict Mode](/reference/react/StrictMode) вместе с [плагином ESLint для React](https://www.npmjs.com/package/eslint-plugin-react-hooks), чтобы помочь вашей кодовой базе следовать Правилам React. Следуя Правилам React, вы сможете находить и устранять эти ошибки и поддерживать ваше приложение в рабочем состоянии. --- -## Components and Hooks must be pure {/*components-and-hooks-must-be-pure*/} +## Компоненты и хуки должны быть чистыми {/*components-and-hooks-must-be-pure*/} -[Purity in Components and Hooks](/reference/rules/components-and-hooks-must-be-pure) is a key rule of React that makes your app predictable, easy to debug, and allows React to automatically optimize your code. +[Чистота компонентов и хуков](/reference/rules/components-and-hooks-must-be-pure) — это ключевое правило React, которое делает ваше приложение предсказуемым, легким для отладки и позволяет React автоматически оптимизировать ваш код. -* [Components must be idempotent](/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent) – React components are assumed to always return the same output with respect to their inputs – props, state, and context. -* [Side effects must run outside of render](/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) – Side effects should not run in render, as React can render components multiple times to create the best possible user experience. -* [Props and state are immutable](/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable) – A component’s props and state are immutable snapshots with respect to a single render. Never mutate them directly. -* [Return values and arguments to Hooks are immutable](/reference/rules/components-and-hooks-must-be-pure#return-values-and-arguments-to-hooks-are-immutable) – Once values are passed to a Hook, you should not modify them. Like props in JSX, values become immutable when passed to a Hook. -* [Values are immutable after being passed to JSX](/reference/rules/components-and-hooks-must-be-pure#values-are-immutable-after-being-passed-to-jsx) – Don’t mutate values after they’ve been used in JSX. Move the mutation before the JSX is created. +* [Компоненты должны быть идемпотентными](/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent) — Предполагается, что компоненты React всегда возвращают одинаковый результат относительно своих входных данных — пропсов, состояния и контекста. +* [Побочные эффекты должны выполняться вне рендеринга](/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) — Побочные эффекты не должны выполняться во время рендеринга, поскольку React может рендерить компоненты несколько раз для создания наилучшего пользовательского опыта. +* [Пропсы и состояние неизменяемы](/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable) — Пропсы и состояние компонента являются неизменяемыми снимками относительно одного рендеринга. Никогда не изменяйте их напрямую. +* [Возвращаемые значения и аргументы для хуков неизменяемы](/reference/rules/components-and-hooks-must-be-pure#return-values-and-arguments-to-hooks-are-immutable) — После того как значения переданы хуку, вы не должны их изменять. Как и пропсы в JSX, значения становятся неизменяемыми при передаче хуку. +* [Значения неизменяемы после передачи в JSX](/reference/rules/components-and-hooks-must-be-pure#values-are-immutable-after-being-passed-to-jsx) — Не изменяйте значения после их использования в JSX. Переместите изменение до создания JSX. --- -## React calls Components and Hooks {/*react-calls-components-and-hooks*/} +## React вызывает компоненты и хуки {/*react-calls-components-and-hooks*/} -[React is responsible for rendering components and hooks when necessary to optimize the user experience.](/reference/rules/react-calls-components-and-hooks) It is declarative: you tell React what to render in your component’s logic, and React will figure out how best to display it to your user. +[React отвечает за рендеринг компонентов и хуков при необходимости для оптимизации пользовательского опыта.](/reference/rules/react-calls-components-and-hooks) Это декларативно: вы говорите React, что рендерить в логике вашего компонента, а React сам определит, как лучше всего отобразить это вашему пользователю. -* [Never call component functions directly](/reference/rules/react-calls-components-and-hooks#never-call-component-functions-directly) – Components should only be used in JSX. Don’t call them as regular functions. -* [Never pass around hooks as regular values](/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values) – Hooks should only be called inside of components. Never pass it around as a regular value. +* [Никогда не вызывайте функции компонентов напрямую](/reference/rules/react-calls-components-and-hooks#never-call-component-functions-directly) — Компоненты следует использовать только в JSX. Не вызывайте их как обычные функции. +* [Никогда не передавайте хуки как обычные значения](/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values) — Хуки следует вызывать только внутри компонентов. Никогда не передавайте их как обычные значения. --- -## Rules of Hooks {/*rules-of-hooks*/} +## Правила хуков {/*rules-of-hooks*/} -Hooks are defined using JavaScript functions, but they represent a special type of reusable UI logic with restrictions on where they can be called. You need to follow the [Rules of Hooks](/reference/rules/rules-of-hooks) when using them. - -* [Only call Hooks at the top level](/reference/rules/rules-of-hooks#only-call-hooks-at-the-top-level) – Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. -* [Only call Hooks from React functions](/reference/rules/rules-of-hooks#only-call-hooks-from-react-functions) – Don’t call Hooks from regular JavaScript functions. +Хуки определяются с использованием функций JavaScript, но они представляют собой особый тип повторно используемой логики пользовательского интерфейса с ограничениями на то, где они могут быть вызваны. Вы должны следовать [Правилам хуков](/reference/rules/rules-of-hooks) при их использовании. +* [Вызывайте хуки только на верхнем уровне](/reference/rules/rules-of-hooks#only-call-hooks-at-the-top-level) — Не вызывайте хуки внутри циклов, условий или вложенных функций. Вместо этого всегда используйте хуки на верхнем уровне вашей функции React, перед любыми ранними возвратами. +* [Вызывайте хуки только из функций React](/reference/rules/rules-of-hooks#only-call-hooks-from-react-functions) — Не вызывайте хуки из обычных функций JavaScript.