diff --git a/src/content/reference/rules/rules-of-hooks.md b/src/content/reference/rules/rules-of-hooks.md index ecaef7c60d..75492c4e5e 100644 --- a/src/content/reference/rules/rules-of-hooks.md +++ b/src/content/reference/rules/rules-of-hooks.md @@ -3,51 +3,51 @@ title: 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. +Хуки определяются с помощью функций JavaScript, но они представляют собой особый тип повторно используемой логики пользовательского интерфейса с ограничениями на то, где они могут быть вызваны. --- -## Only call Hooks at the top level {/*only-call-hooks-at-the-top-level*/} +## Только вызывайте хуки на верхнем уровне {/*only-call-hooks-at-the-top-level*/} -Functions whose names start with `use` are called [*Hooks*](/reference/react) in React. +Функции, имена которых начинаются с `use`, называются [*хуками*](/reference/react) в React. -**Don’t call Hooks inside loops, conditions, nested functions, or `try`/`catch`/`finally` blocks.** Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component: +**Не вызывайте хуки внутри циклов, условий, вложенных функций или блоков `try`/`catch`/`finally`.** Вместо этого всегда используйте хуки на верхнем уровне вашей функции React, перед любыми досрочными возвратами. Вы можете вызывать хуки только во время рендеринга компонента функции React: -* ✅ Call them at the top level in the body of a [function component](/learn/your-first-component). -* ✅ Call them at the top level in the body of a [custom Hook](/learn/reusing-logic-with-custom-hooks). +* ✅ Вызывайте их на верхнем уровне в теле [компонента функции](/learn/your-first-component). +* ✅ Вызывайте их на верхнем уровне в теле [пользовательского хука](/learn/reusing-logic-with-custom-hooks). ```js{2-3,8-9} function Counter() { - // ✅ Good: top-level in a function component + // ✅ Хорошо: на верхнем уровне в компоненте функции const [count, setCount] = useState(0); // ... } function useWindowWidth() { - // ✅ Good: top-level in a custom Hook + // ✅ Хорошо: на верхнем уровне в пользовательском хуке const [width, setWidth] = useState(window.innerWidth); // ... } ``` -It’s **not** supported to call Hooks (functions starting with `use`) in any other cases, for example: +Вызов хуков (функций, начинающихся с `use`) в других случаях **не** поддерживается, например: -* 🔴 Do not call Hooks inside conditions or loops. -* 🔴 Do not call Hooks after a conditional `return` statement. -* 🔴 Do not call Hooks in event handlers. -* 🔴 Do not call Hooks in class components. -* 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or `useEffect`. -* 🔴 Do not call Hooks inside `try`/`catch`/`finally` blocks. +* 🔴 Не вызывайте хуки внутри условий или циклов. +* 🔴 Не вызывайте хуки после условного оператора `return`. +* 🔴 Не вызывайте хуки в обработчиках событий. +* 🔴 Не вызывайте хуки в классовых компонентах. +* 🔴 Не вызывайте хуки внутри функций, передаваемых в `useMemo`, `useReducer` или `useEffect`. +* 🔴 Не вызывайте хуки внутри блоков `try`/`catch`/`finally`. -If you break these rules, you might see this error. +Если вы нарушите эти правила, вы можете увидеть эту ошибку. ```js{3-4,11-12,20-21} function Bad({ cond }) { if (cond) { - // 🔴 Bad: inside a condition (to fix, move it outside!) + // 🔴 Плохо: внутри условия (чтобы исправить, вынесите его наружу!) const theme = useContext(ThemeContext); } // ... @@ -55,7 +55,7 @@ function Bad({ cond }) { function Bad() { for (let i = 0; i < 10; i++) { - // 🔴 Bad: inside a loop (to fix, move it outside!) + // 🔴 Плохо: внутри цикла (чтобы исправить, вынесите его наружу!) const theme = useContext(ThemeContext); } // ... @@ -65,14 +65,14 @@ function Bad({ cond }) { if (cond) { return; } - // 🔴 Bad: after a conditional return (to fix, move it before the return!) + // 🔴 Плохо: после условного возврата (чтобы исправить, переместите его перед return!) const theme = useContext(ThemeContext); // ... } function Bad() { function handleClick() { - // 🔴 Bad: inside an event handler (to fix, move it outside!) + // 🔴 Плохо: внутри обработчика события (чтобы исправить, вынесите его наружу!) const theme = useContext(ThemeContext); } // ... @@ -80,7 +80,7 @@ function Bad() { function Bad() { const style = useMemo(() => { - // 🔴 Bad: inside useMemo (to fix, move it outside!) + // 🔴 Плохо: внутри useMemo (чтобы исправить, вынесите его наружу!) const theme = useContext(ThemeContext); return createStyle(theme); }); @@ -89,7 +89,7 @@ function Bad() { class Bad extends React.Component { render() { - // 🔴 Bad: inside a class component (to fix, write a function component instead of a class!) + // 🔴 Плохо: внутри классового компонента (чтобы исправить, напишите компонент функции вместо класса!) useEffect(() => {}) // ... } @@ -97,7 +97,7 @@ class Bad extends React.Component { function Bad() { try { - // 🔴 Bad: inside try/catch/finally block (to fix, move it outside!) + // 🔴 Плохо: внутри блока try/catch/finally (чтобы исправить, вынесите его наружу!) const [x, setX] = useState(0); } catch { const [x, setX] = useState(1); @@ -105,31 +105,31 @@ function Bad() { } ``` -You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to catch these mistakes. +Вы можете использовать плагин [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) для отлова этих ошибок. -[Custom Hooks](/learn/reusing-logic-with-custom-hooks) *may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a function component is rendering. +[Пользовательские хуки](/learn/reusing-logic-with-custom-hooks) *могут* вызывать другие хуки (в этом их основное назначение). Это работает, потому что пользовательские хуки также должны вызываться только во время рендеринга компонента функции. --- -## Only call Hooks from React functions {/*only-call-hooks-from-react-functions*/} +## Вызывайте хуки только из функций React {/*only-call-hooks-from-react-functions*/} -Don’t call Hooks from regular JavaScript functions. Instead, you can: +Не вызывайте хуки из обычных функций JavaScript. Вместо этого вы можете: -✅ Call Hooks from React function components. -✅ Call Hooks from [custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component). +✅ Вызывать хуки из компонентов функций React. +✅ Вызывать хуки из [пользовательских хуков](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component). -By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code. +Следуя этому правилу, вы гарантируете, что вся логика состояния в компоненте будет четко видна из его исходного кода. ```js {2,5} function FriendList() { const [onlineStatus, setOnlineStatus] = useOnlineStatus(); // ✅ } -function setOnlineStatus() { // ❌ Not a component or custom Hook! +function setOnlineStatus() { // ❌ Не компонент и не пользовательский хук! const [onlineStatus, setOnlineStatus] = useOnlineStatus(); } ```