diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index ce06e7035..9442e3ef9 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` це хук, який дозволяє читати [контекст](/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,42 +30,42 @@ 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. +* Eлементи-провайдери не впливають на виклик `useContext()` у компоненті, з якого й повертаються. Відповідний `` **повинен бути розташований *вище*** компонента, що викликає `useContext()`. +* React **автоматично оновлює** всі дочірні компоненти, які використовують певний контекст, починаючи з провайдера, що отримує змінене значення `value`. Попереднє та наступне значення порівнюються за допомогою [`Object.is`](https://webdoky.org/uk/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'; function Button() { const theme = useContext(ThemeContext); - // ... + // ... ``` -`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()`. @@ -106,9 +106,9 @@ export default function MyApp() { function Form() { return ( - - - + + + ); } @@ -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`, а також викликати останню за потреби. @@ -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 ( + }}>Увійти як Advika ); } @@ -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,7 +427,7 @@ 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 ( - - - + + +