`, and any DOM node inside of it, no matter how deep, will inherit that color unless some other DOM node in the middle overrides it with `color: green`. Similarly, in React, the only way to override some context coming from above is to wrap children into a context provider with a different value.
-
-In CSS, different properties like `color` and `background-color` don't override each other. You can set all `
`'s `color` to red without impacting `background-color`. Similarly, **different React contexts don't override each other.** Each context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* context. One component may use or provide many different contexts without a problem.
-
-## Before you use context {/*before-you-use-context*/}
-
-Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into context.**
-
-Here's a few alternatives you should consider before using context:
-
-1. **Start by [passing props.](/learn/passing-props-to-a-component)** If your components are not trivial, it's not unusual to pass a dozen props down through a dozen components. It may feel like a slog, but it makes it very clear which components use which data! The person maintaining your code will be glad you've made the data flow explicit with props.
-2. **Extract components and [pass JSX as `children`](/learn/passing-props-to-a-component#passing-jsx-as-children) to them.** If you pass some data through many layers of intermediate components that don't use that data (and only pass it further down), this often means that you forgot to extract some components along the way. For example, maybe you pass data props like `posts` to visual components that don't use them directly, like `
`. Instead, make `Layout` take `children` as a prop, and render `
`. This reduces the number of layers between the component specifying the data and the one that needs it.
-
-If neither of these approaches works well for you, consider context.
-
-## Use cases for context {/*use-cases-for-context*/}
-
-* **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look.
-* **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value.
-* **Routing:** Most routing solutions use context internally to hold the current route. This is how every link "knows" whether it's active or not. If you build your own router, you might want to do it too.
-* **Managing state:** As your app grows, you might end up with a lot of state closer to the top of your app. Many distant components below may want to change it. It is common to [use a reducer together with context](/learn/scaling-up-with-reducer-and-context) to manage complex state and pass it down to distant components without too much hassle.
+* **Тематизация:** Если ваше приложение позволяет пользователю изменять его внешний вид (например, тёмный режим), вы можете поместить `Context.Provider` в верхнюю часть приложения и использовать этот контекст в компонентах, которым нужно настроить свой внешний вид.
+* **Текущая учётная запись:** Многим компонентам может потребоваться знать, какой пользователь вошёл в систему в данный момент. Помещение этой информации в контекст делает её удобной для чтения в любом месте дерева компонентов. Некоторые приложения также позволяют работать с несколькими учётными записями одновременно (например, чтобы оставить комментарий от имени другого пользователя). В таких случаях может быть удобно обернуть часть пользовательского интерфейса во вложенный `Provider` с другим значением текущей учётной записи.
+* **Маршрутизация:** Большинство решений для маршрутизации используют контекст внутри себя для хранения текущего маршрута. Именно так каждая ссылка "знает", активна она или нет. Если вы создаёте собственный маршрутизатор, вам, возможно, тоже захочется это сделать.
+* **Управление состоянием:** По мере роста вашего приложения вы можете обнаружить, что много состояния находится ближе к вершине дерева компонентов. Многим удалённым компонентам ниже может потребоваться изменить его. Часто [используют редюсер вместе с контекстом](/learn/scaling-up-with-reducer-and-context) для управления сложным состоянием и передачи его удалённым компонентам без особых усилий.
-Context is not limited to static values. If you pass a different value on the next render, React will update all the components reading it below! This is why context is often used in combination with state.
+Контекст не ограничивается статическими значениями. Если вы передадите другое значение при следующем рендеринге, React обновит все компоненты, которые его читают ниже! Именно поэтому контекст часто используется в сочетании с состоянием.
-In general, if some information is needed by distant components in different parts of the tree, it's a good indication that context will help you.
+В целом, если какая-либо информация требуется удалённым компонентам в разных частях дерева, это хороший признак того, что контекст вам поможет.
-* Context lets a component provide some information to the entire tree below it.
-* To pass context:
- 1. Create and export it with `export const MyContext = createContext(defaultValue)`.
- 2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep.
- 3. Wrap children into `` to provide it from a parent.
-* Context passes through any components in the middle.
-* Context lets you write components that "adapt to their surroundings".
-* Before you use context, try passing props or passing JSX as `children`.
+* Контекст позволяет компоненту предоставлять некоторую информацию всему дереву ниже него.
+* Для передачи контекста:
+ 1. Создайте и экспортируйте его с помощью `export const MyContext = createContext(defaultValue)`.
+ 2. Передайте его в хук `useContext(MyContext)` для чтения в любом дочернем компоненте, независимо от его глубины.
+ 3. Оберните дочерние элементы в `` для предоставления его от родителя.
+* Контекст передаётся через любые промежуточные компоненты.
+* Контекст позволяет писать компоненты, которые "адаптируются к своему окружению".
+* Прежде чем использовать контекст, попробуйте передать пропсы или JSX в качестве `children`.
-#### Replace prop drilling with context {/*replace-prop-drilling-with-context*/}
+#### Замените передачу пропсов через несколько уровней на контекст {/*replace-prop-drilling-with-context*/}
-In this example, toggling the checkbox changes the `imageSize` prop passed to each ``. The checkbox state is held in the top-level `App` component, but each `` needs to be aware of it.
+В этом примере переключение флажка изменяет пропс `imageSize`, передаваемый каждому ``. Состояние флажка хранится в компоненте верхнего уровня `App`, но каждый `` должен быть осведомлён о нём.
-Currently, `App` passes `imageSize` to `List`, which passes it to each `Place`, which passes it to the `PlaceImage`. Remove the `imageSize` prop, and instead pass it from the `App` component directly to `PlaceImage`.
+В настоящее время `App` передаёт `imageSize` в `List`, который передаёт его каждому `Place`, который передаёт его `PlaceImage`. Удалите пропс `imageSize` и вместо этого передайте его из компонента `App` напрямую в `PlaceImage`.
-You can declare context in `Context.js`.
+Вы можете объявить контекст в `Context.js`.
@@ -975,7 +586,7 @@ export const places = [{
}, {
id: 3,
name: 'Selarón Staircase in Rio de Janeiro, Brazil',
- description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people."',
+ description: 'This landmark was created by Jorge Selarón, a Chilean-born artist, as a "tribute to the Brazilian people".',
imageId: 'aeO3rpI'
}, {
id: 4,
@@ -1020,9 +631,9 @@ li {
-Remove `imageSize` prop from all the components.
+Удалите пропс `imageSize` из всех компонентов.
-Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`:
+Создайте и экспортируйте `ImageSizeContext` из `Context.js`. Затем оберните `List` в `` для передачи значения вниз и используйте `useContext(ImageSizeContext)` для его чтения в `PlaceImage`:
@@ -1157,8 +768,8 @@ li {
-Note how components in the middle don't need to pass `imageSize` anymore.
+Обратите внимание, как промежуточные компоненты больше не передают `imageSize`.
-
+
\ No newline at end of file