diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index ce06e7035..05e7ecdad 100644 --- a/src/content/reference/react/useContext.md +++ b/src/content/reference/react/useContext.md @@ -4,7 +4,7 @@ title: useContext -`useContext` is a React Hook that lets you read and subscribe to [context](/learn/passing-data-deeply-with-context) from your component. +`useContext` — это хук React, который позволяет читать и подписываться на [контекст](/learn/passing-data-deeply-with-context) из вашего компонента. ```js const value = useContext(SomeContext) @@ -16,11 +16,11 @@ const value = useContext(SomeContext) --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `useContext(SomeContext)` {/*usecontext*/} -Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context) +Вызовите `useContext` на верхнем уровне вашего компонента, чтобы читать и подписываться на [контекст.](/learn/passing-data-deeply-with-context) ```js import { useContext } from 'react'; @@ -30,30 +30,30 @@ function MyComponent() { // ... ``` -[See more examples below.](#usage) +[Больше примеров ниже.](#usage) -#### Parameters {/*parameters*/} +#### Параметры {/*parameters*/} -* `SomeContext`: The context that you've previously created with [`createContext`](/reference/react/createContext). The context itself does not hold the information, it only represents the kind of information you can provide or read from components. +* `SomeContext`: Контекст, который вы ранее создали с помощью [`createContext`](/reference/react/createContext). Сам контекст не хранит информацию, он только представляет тип информации, которую вы можете передавать или читать из компонентов. -#### Returns {/*returns*/} +#### Возвращаемое значение {/*returns*/} -`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/reference/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes. +`useContext` возвращает значение контекста для вызывающего компонента. Оно определяется как `value`, переданное ближайшему `SomeContext.Provider` выше вызывающего компонента в дереве. Если такого провайдера нет, то возвращаемое значение будет `defaultValue`, которое вы передали в [`createContext`](/reference/react/createContext) для этого контекста. Возвращаемое значение всегда актуально. React автоматически перерендерит компоненты, которые читают контекст, если он изменится. -#### Caveats {/*caveats*/} +#### Предупреждения {/*caveats*/} -* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `` **needs to be *above*** the component doing the `useContext()` call. -* React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/reference/react/memo) does not prevent the children receiving fresh context values. -* If your build system produces duplicates modules in the output (which can happen with symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison. +* Вызов `useContext()` в компоненте не затрагивается провайдерами, возвращёнными из *того же самого* компонента. Соответствующий `` **должен быть *выше*** компонента, который вызывает `useContext()`. +* React **автоматически перерендерит** всех потомков, которые используют определённый контекст, начиная с провайдера, который получил другое `value`. Предыдущее и следующее значения сравниваются с помощью [`Object.is`](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Пропуск повторных рендеров с помощью [`memo`](/reference/react/memo) не помешает потомкам получить свежие значения контекста. +* Если ваша система сборки создаёт дублирующиеся модули в выходных данных (что может произойти при использовании символических ссылок), это может сломать контекст. Передача чего-либо через контекст работает только если `SomeContext`, который вы используете для передачи контекста, и `SomeContext`, который вы используете для его чтения, — это ***в точности* один и тот же объект**, что определяется сравнением `===`. --- -## Usage {/*usage*/} +## Использование {/*usage*/} -### Passing data deeply into the tree {/*passing-data-deeply-into-the-tree*/} +### Передача данных глубоко в дерево {/*passing-data-deeply-into-the-tree*/} -Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context) +Вызовите `useContext` на верхнем уровне вашего компонента, чтобы читать и подписываться на [контекст.](/learn/passing-data-deeply-with-context) ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { useContext } from 'react'; @@ -63,9 +63,9 @@ function Button() { // ... ``` -`useContext` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. +`useContext` возвращает значение контекста для переданного контекста. Чтобы определить значение контекста, React ищет по дереву компонентов и находит **ближайший провайдер контекста выше** для этого конкретного контекста. -To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider: +Чтобы передать контекст в `Button`, оберните его или один из его родительских компонентов в соответствующий провайдер контекста: ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -77,15 +77,15 @@ function MyPage() { } function Form() { - // ... renders buttons inside ... + // ... рендерит кнопки внутри ... } ``` -It doesn't matter how many layers of components there are between the provider and the `Button`. When a `Button` *anywhere* inside of `Form` calls `useContext(ThemeContext)`, it will receive `"dark"` as the value. +Не имеет значения, сколько слоёв компонентов находится между провайдером и `Button`. Когда `Button` *где угодно* внутри `Form` вызывает `useContext(ThemeContext)`, он получит `"dark"` в качестве значения. -`useContext()` always looks for the closest provider *above* the component that calls it. It searches upwards and **does not** consider providers in the component from which you're calling `useContext()`. +`useContext()` всегда ищет ближайший провайдер *выше* компонента, который его вызывает. Он ищет вверх и **не учитывает** провайдеры в компоненте, из которого вы вызываете `useContext()`. @@ -175,9 +175,9 @@ function Button({ children }) { --- -### Updating data passed via context {/*updating-data-passed-via-context*/} +### Обновление данных, передаваемых через контекст {/*updating-data-passed-via-context*/} -Often, you'll want the context to change over time. To update context, combine it with [state.](/reference/react/useState) Declare a state variable in the parent component, and pass the current state down as the context value to the provider. +Часто вы захотите изменять контекст со временем. Чтобы обновить контекст, совместите его с [состоянием.](/reference/react/useState) Объявите переменную состояния в родительском компоненте и передайте текущее состояние вниз как значение контекста провайдеру. ```js {2} [[1, 4, "ThemeContext"], [2, 4, "theme"], [1, 11, "ThemeContext"]] function MyPage() { @@ -188,20 +188,20 @@ function MyPage() { ); } ``` -Now any `Button` inside of the provider will receive the current `theme` value. If you call `setTheme` to update the `theme` value that you pass to the provider, all `Button` components will re-render with the new `'light'` value. +Теперь любой `Button` внутри провайдера будет получать текущее значение `theme`. Если вы вызовете `setTheme` для обновления значения `theme`, которое вы передаёте провайдеру, все компоненты `Button` перерендерятся с новым значением `'light'`. - + -#### Updating a value via context {/*updating-a-value-via-context*/} +#### Обновление значения через контекст {/*updating-a-value-via-context*/} -In this example, the `MyApp` component holds a state variable which is then passed to the `ThemeContext` provider. Checking the "Dark mode" checkbox updates the state. Changing the provided value re-renders all the components using that context. +В этом примере компонент `MyApp` содержит переменную состояния, которая затем передаётся провайдеру `ThemeContext`. Установка флажка "Тёмный режим" обновляет состояние. Изменение переданного значения перерендерит все компоненты, использующие этот контекст. @@ -223,7 +223,7 @@ export default function MyApp() { setTheme(e.target.checked ? 'dark' : 'light') }} /> - Use dark mode + Использовать тёмный режим ) @@ -231,9 +231,9 @@ export default function MyApp() { function Form({ children }) { return ( - - - + + + ); } @@ -299,13 +299,13 @@ function Button({ children }) { -Note that `value="dark"` passes the `"dark"` string, but `value={theme}` passes the value of the JavaScript `theme` variable with [JSX curly braces.](/learn/javascript-in-jsx-with-curly-braces) Curly braces also let you pass context values that aren't strings. +Обратите внимание, что `value="dark"` передаёт строку `"dark"`, но `value={theme}` передаёт значение JavaScript-переменной `theme` с помощью [JSX-фигурных скобок.](/learn/javascript-in-jsx-with-curly-braces) Фигурные скобки также позволяют передавать значения контекста, которые не являются строками. -#### Updating an object via context {/*updating-an-object-via-context*/} +#### Обновление объекта через контекст {/*updating-an-object-via-context*/} -In this example, there is a `currentUser` state variable which holds an object. You combine `{ currentUser, setCurrentUser }` into a single object and pass it down through the context inside the `value={}`. This lets any component below, such as `LoginButton`, read both `currentUser` and `setCurrentUser`, and then call `setCurrentUser` when needed. +В этом примере есть переменная состояния `currentUser`, которая хранит объект. Вы объединяете `{ currentUser, setCurrentUser }` в один объект и передаёте его вниз через контекст внутри `value={}`. Это позволяет любому компоненту ниже, например `LoginButton`, читать и `currentUser`, и `setCurrentUser`, а затем вызывать `setCurrentUser` при необходимости. @@ -330,7 +330,7 @@ export default function MyApp() { function Form({ children }) { return ( - + ); @@ -343,13 +343,13 @@ function LoginButton() { } = useContext(CurrentUserContext); if (currentUser !== null) { - return

You logged in as {currentUser.name}.

; + return

Вы вошли как {currentUser.name}.

; } return ( + setCurrentUser({ name: 'Адвика' }) + }}>Войти как Адвика ); } @@ -395,9 +395,9 @@ label { -#### Multiple contexts {/*multiple-contexts*/} +#### Множественные контексты {/*multiple-contexts*/} -In this example, there are two independent contexts. `ThemeContext` provides the current theme, which is a string, while `CurrentUserContext` holds the object representing the current user. +В этом примере есть два независимых контекста. `ThemeContext` предоставляет текущую тему, которая является строкой, а `CurrentUserContext` хранит объект, представляющий текущего пользователя. @@ -427,8 +427,8 @@ export default function MyApp() { setTheme(e.target.checked ? 'dark' : 'light') }} /> - Use dark mode - +Использовать тёмный режим + ) @@ -437,7 +437,7 @@ export default function MyApp() { function WelcomePanel({ children }) { const {currentUser} = useContext(CurrentUserContext); return ( - + {currentUser !== null ? : @@ -449,7 +449,7 @@ function WelcomePanel({ children }) { function Greeting() { const {currentUser} = useContext(CurrentUserContext); return ( -

You logged in as {currentUser.name}.

+

Вы вошли как {currentUser.name}.

) } @@ -461,7 +461,7 @@ function LoginForm() { return ( <> ); @@ -612,7 +612,7 @@ function MyProviders({ children, theme, setTheme }) { function WelcomePanel({ children }) { const {currentUser} = useContext(CurrentUserContext); return ( - + {currentUser !== null ? : @@ -624,7 +624,7 @@ function WelcomePanel({ children }) { function Greeting() { const {currentUser} = useContext(CurrentUserContext); return ( -

You logged in as {currentUser.name}.

+

Вы вошли как {currentUser.name}.

) } @@ -636,7 +636,7 @@ function LoginForm() { return ( <> ); @@ -947,25 +947,25 @@ ul, li { margin: 0; padding: 0; } --- -### Specifying a fallback default value {/*specifying-a-fallback-default-value*/} +### Указание запасного значения по умолчанию {/*specifying-a-fallback-default-value*/} -If React can't find any providers of that particular context in the parent tree, the context value returned by `useContext()` will be equal to the default value that you specified when you [created that context](/reference/react/createContext): +Если React не может найти ни одного провайдера этого конкретного контекста в родительском дереве, значение контекста, возвращаемое `useContext()`, будет равно значению по умолчанию, которое вы указали при [создании этого контекста](/reference/react/createContext): ```js [[1, 1, "ThemeContext"], [3, 1, "null"]] const ThemeContext = createContext(null); ``` -The default value **never changes**. If you want to update context, use it with state as [described above.](#updating-data-passed-via-context) +Значение по умолчанию **никогда не меняется**. Если вы хотите обновить контекст, используйте его с состоянием, как [описано выше.](#updating-data-passed-via-context) -Often, instead of `null`, there is some more meaningful value you can use as a default, for example: +Часто вместо `null` можно использовать более осмысленное значение по умолчанию, например: ```js [[1, 1, "ThemeContext"], [3, 1, "light"]] const ThemeContext = createContext('light'); ``` -This way, if you accidentally render some component without a corresponding provider, it won't break. This also helps your components work well in a test environment without setting up a lot of providers in the tests. +Таким образом, если вы случайно отрендерите какой-то компонент без соответствующего провайдера, он не сломается. Это также помогает вашим компонентам хорошо работать в тестовой среде без настройки множества провайдеров в тестах. -In the example below, the "Toggle theme" button is always light because it's **outside any theme context provider** and the default context theme value is `'light'`. Try editing the default theme to be `'dark'`. +В примере ниже кнопка "Переключить тему" всегда светлая, потому что она находится **вне любого провайдера контекста темы**, и значение контекста темы по умолчанию — `'light'`. Попробуйте изменить тему по умолчанию на `'dark'`. @@ -984,7 +984,7 @@ export default function MyApp() { ) @@ -992,9 +992,9 @@ export default function MyApp() { function Form({ children }) { return ( - - - + + + ); } @@ -1062,9 +1062,9 @@ function Button({ children, onClick }) { --- -### Overriding context for a part of the tree {/*overriding-context-for-a-part-of-the-tree*/} +### Переопределение контекста для части дерева {/*overriding-context-for-a-part-of-the-tree*/} -You can override the context for a part of the tree by wrapping that part in a provider with a different value. +Вы можете переопределить контекст для части дерева, обернув эту часть в провайдер с другим значением. ```js {3,5} @@ -1076,13 +1076,13 @@ You can override the context for a part of the tree by wrapping that part in a p ``` -You can nest and override providers as many times as you need. +Вы можете вкладывать и переопределять провайдеры столько раз, сколько нужно. - + -#### Overriding a theme {/*overriding-a-theme*/} +#### Переопределение темы {/*overriding-a-theme*/} -Here, the button *inside* the `Footer` receives a different context value (`"light"`) than the buttons outside (`"dark"`). +Здесь кнопка *внутри* `Footer` получает другое значение контекста (`"light"`), чем кнопки снаружи (`"dark"`). @@ -1101,9 +1101,9 @@ export default function MyApp() { function Form() { return ( - - - + + +