You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/reference/react/useContext.md
+34-34Lines changed: 34 additions & 34 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ title: useContext
4
4
5
5
<Intro>
6
6
7
-
`useContext` is a React Hook that lets you read and subscribe to [context](/learn/passing-data-deeply-with-context) from your component.
7
+
`useContext` is a React Hook that lets you read and subscribe to [Context](/learn/passing-data-deeply-with-context) from your component.
8
8
9
9
```js
10
10
constvalue=useContext(SomeContext)
@@ -20,7 +20,7 @@ const value = useContext(SomeContext)
20
20
21
21
### `useContext(SomeContext)` {/*usecontext*/}
22
22
23
-
Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context)
23
+
Call `useContext` at the top level of your component to read and subscribe to [Context.](/learn/passing-data-deeply-with-context)
24
24
25
25
```js
26
26
import { useContext } from'react';
@@ -34,17 +34,17 @@ function MyComponent() {
34
34
35
35
#### Parameters {/*parameters*/}
36
36
37
-
* `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.
37
+
* `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.
38
38
39
39
#### Returns {/*returns*/}
40
40
41
-
`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext` 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.
41
+
`useContext` returns the Context value for the calling component. It is determined as the `value` passed to the closest `SomeContext` 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.
42
42
43
43
#### Caveats {/*caveats*/}
44
44
45
45
* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `<Context>` **needs to be *above*** the component doing the `useContext()` call.
46
-
* 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.
47
-
* 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.
46
+
* 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.
47
+
* 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.
48
48
49
49
---
50
50
@@ -53,7 +53,7 @@ function MyComponent() {
53
53
54
54
### Passing data deeply into the tree {/*passing-data-deeply-into-the-tree*/}
55
55
56
-
Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context)
56
+
Call `useContext` at the top level of your component to read and subscribe to [Context.](/learn/passing-data-deeply-with-context)
57
57
58
58
```js [[2, 4, "theme"], [1, 4, "ThemeContext"]]
59
59
import { useContext } from'react';
@@ -63,9 +63,9 @@ function Button() {
63
63
// ...
64
64
```
65
65
66
-
`useContext` returns the <CodeStep step={2}>context value</CodeStep> for the <CodeStep step={1}>context</CodeStep> you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context.
66
+
`useContext` returns the <CodeStep step={2}>Context value</CodeStep> for the <CodeStep step={1}>Context</CodeStep> you passed. To determine the Context value, React searches the component tree and finds **the closest Context provider above** for that particular Context.
67
67
68
-
To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider:
68
+
To pass Context to a `Button`, wrap it or one of its parent components into the corresponding Context provider:
@@ -175,9 +175,9 @@ function Button({ children }) {
175
175
176
176
---
177
177
178
-
### Updating data passed via context {/*updating-data-passed-via-context*/}
178
+
### Updating data passed via Context {/*updating-data-passed-via-context*/}
179
179
180
-
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 <CodeStep step={2}>context value</CodeStep> to the provider.
180
+
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 <CodeStep step={2}>Context value</CodeStep> to the provider.
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.
199
199
200
-
<Recipes titleText="Examples of updating context" titleId="examples-basic">
200
+
<Recipes titleText="Examples of updating Context" titleId="examples-basic">
201
201
202
-
#### Updating a value via context {/*updating-a-value-via-context*/}
202
+
#### Updating a value via Context {/*updating-a-value-via-context*/}
203
203
204
-
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.
204
+
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.
205
205
206
206
<Sandpack>
207
207
@@ -299,13 +299,13 @@ function Button({ children }) {
299
299
300
300
</Sandpack>
301
301
302
-
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.
302
+
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.
303
303
304
304
<Solution />
305
305
306
-
#### Updating an object via context {/*updating-an-object-via-context*/}
306
+
#### Updating an object via Context {/*updating-an-object-via-context*/}
307
307
308
-
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.
308
+
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.
309
309
310
310
<Sandpack>
311
311
@@ -395,9 +395,9 @@ label {
395
395
396
396
<Solution />
397
397
398
-
#### Multiple contexts {/*multiple-contexts*/}
398
+
#### Multiple Contexts {/*multiple-contexts*/}
399
399
400
-
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.
400
+
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.
401
401
402
402
<Sandpack>
403
403
@@ -564,7 +564,7 @@ label {
564
564
565
565
#### Extracting providers to a component {/*extracting-providers-to-a-component*/}
566
566
567
-
As your app grows, it is expected that you'll have a "pyramid" of contexts closer to the root of your app. There is nothing wrong with that. However, if you dislike the nesting aesthetically, you can extract the providers into a single component. In this example, `MyProviders` hides the "plumbing" and renders the children passed to it inside the necessary providers. Note that the `theme` and `setTheme` state is needed in `MyApp` itself, so `MyApp` still owns that piece of the state.
567
+
As your app grows, it is expected that you'll have a "pyramid" of Contexts closer to the root of your app. There is nothing wrong with that. However, if you dislike the nesting aesthetically, you can extract the providers into a single component. In this example, `MyProviders` hides the "plumbing" and renders the children passed to it inside the necessary providers. Note that the `theme` and `setTheme` state is needed in `MyApp` itself, so `MyApp` still owns that piece of the state.
568
568
569
569
<Sandpack>
570
570
@@ -737,9 +737,9 @@ label {
737
737
738
738
<Solution />
739
739
740
-
#### Scaling up with context and a reducer {/*scaling-up-with-context-and-a-reducer*/}
740
+
#### Scaling up with Context and a reducer {/*scaling-up-with-context-and-a-reducer*/}
741
741
742
-
In larger apps, it is common to combine context with a [reducer](/reference/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate contexts.
742
+
In larger apps, it is common to combine Context with a [reducer](/reference/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate Contexts.
743
743
744
744
Read a [full walkthrough](/learn/scaling-up-with-reducer-and-context) of this example.
### Specifying a fallback default value {/*specifying-a-fallback-default-value*/}
951
951
952
-
If React can't find any providers of that particular <CodeStep step={1}>context</CodeStep> in the parent tree, the context value returned by `useContext()` will be equal to the <CodeStep step={3}>default value</CodeStep> that you specified when you [created that context](/reference/react/createContext):
952
+
If React can't find any providers of that particular <CodeStep step={1}>Context</CodeStep> in the parent tree, the Context value returned by `useContext()` will be equal to the <CodeStep step={3}>default value</CodeStep> that you specified when you [created that Context](/reference/react/createContext):
953
953
954
954
```js [[1, 1, "ThemeContext"], [3, 1, "null"]]
955
955
constThemeContext=createContext(null);
956
956
```
957
957
958
-
The default value **never changes**. If you want to update context, use it with state as [described above.](#updating-data-passed-via-context)
958
+
The default value **never changes**. If you want to update Context, use it with state as [described above.](#updating-data-passed-via-context)
959
959
960
960
Often, instead of `null`, there is some more meaningful value you can use as a default, for example:
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.
967
967
968
-
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'`.
968
+
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'`.
969
969
970
970
<Sandpack>
971
971
@@ -1062,9 +1062,9 @@ function Button({ children, onClick }) {
1062
1062
1063
1063
---
1064
1064
1065
-
### Overriding context for a part of the tree {/*overriding-context-for-a-part-of-the-tree*/}
1065
+
### Overriding Context for a part of the tree {/*overriding-context-for-a-part-of-the-tree*/}
1066
1066
1067
-
You can override the context for a part of the tree by wrapping that part in a provider with a different value.
1067
+
You can override the Context for a part of the tree by wrapping that part in a provider with a different value.
1068
1068
1069
1069
```js {3,5}
1070
1070
<ThemeContext value="dark">
@@ -1078,11 +1078,11 @@ You can override the context for a part of the tree by wrapping that part in a p
1078
1078
1079
1079
You can nest and override providers as many times as you need.
1080
1080
1081
-
<Recipes titleText="Examples of overriding context">
1081
+
<Recipes titleText="Examples of overriding Context">
1082
1082
1083
1083
#### Overriding a theme {/*overriding-a-theme*/}
1084
1084
1085
-
Here, the button *inside* the `Footer` receives a different context value (`"light"`) than the buttons outside (`"dark"`).
1085
+
Here, the button *inside* the `Footer` receives a different Context value (`"light"`) than the buttons outside (`"dark"`).
You can "accumulate" information when you nest context providers. In this example, the `Section` component keeps track of the `LevelContext` which specifies the depth of the section nesting. It reads the `LevelContext` from the parent section, and provides the `LevelContext` number increased by one to its children. As a result, the `Heading` component can automatically decide which of the `<h1>`, `<h2>`, `<h3>`, ..., tags to use based on how many `Section` components it is nested inside of.
1191
+
You can "accumulate" information when you nest Context providers. In this example, the `Section` component keeps track of the `LevelContext` which specifies the depth of the section nesting. It reads the `LevelContext` from the parent section, and provides the `LevelContext` number increased by one to its children. As a result, the `Heading` component can automatically decide which of the `<h1>`, `<h2>`, `<h3>`, ..., tags to use based on how many `Section` components it is nested inside of.
1192
1192
1193
1193
Read a [detailed walkthrough](/learn/passing-data-deeply-with-context) of this example.
### Optimizing re-renders when passing objects and functions {/*optimizing-re-renders-when-passing-objects-and-functions*/}
1292
1292
1293
-
You can pass any values via context, including objects and functions.
1293
+
You can pass any values via Context, including objects and functions.
1294
1294
1295
1295
```js [[2, 10, "{ currentUser, login }"]]
1296
1296
functionMyApp() {
@@ -1309,7 +1309,7 @@ function MyApp() {
1309
1309
}
1310
1310
```
1311
1311
1312
-
Here, the <CodeStep step={2}>context value</CodeStep> is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`.
1312
+
Here, the <CodeStep step={2}>Context value</CodeStep> is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`.
1313
1313
1314
1314
In smaller apps, this is not a problem. However, there is no need to re-render them if the underlying data, like `currentUser`, has not changed. To help React take advantage of that fact, you may wrap the `login` function with [`useCallback`](/reference/react/useCallback) and wrap the object creation into [`useMemo`](/reference/react/useMemo). This is a performance optimization:
1315
1315
@@ -1353,7 +1353,7 @@ There are a few common ways that this can happen:
1353
1353
2. You may have forgotten to wrap your component with `<SomeContext>`, or you might have put it in a different part of the tree than you thought. Check whether the hierarchy is right using [React DevTools.](/learn/react-developer-tools)
1354
1354
3. You might be running into some build issue with your tooling that causes `SomeContext` as seen from the providing component and `SomeContext` as seen by the reading component to be two different objects. This can happen if you use symlinks, for example. You can verify this by assigning them to globals like `window.SomeContext1` and `window.SomeContext2` and then checking whether `window.SomeContext1===window.SomeContext2` in the console. If they're not the same, fix that issue on the build tool level.
1355
1355
1356
-
### I am always getting `undefined` from my context although the default value is different {/*i-am-always-getting-undefined-from-my-context-although-the-default-value-is-different*/}
1356
+
### I am always getting `undefined` from my Context although the default value is different {/*i-am-always-getting-undefined-from-my-context-although-the-default-value-is-different*/}
1357
1357
1358
1358
You might have a provider without a `value` in the tree:
1359
1359
@@ -1384,4 +1384,4 @@ In both of these cases you should see a warning from React in the console. To fi
1384
1384
</ThemeContext>
1385
1385
```
1386
1386
1387
-
Note that the [default value from your `createContext(defaultValue)` call](#specifying-a-fallback-default-value) is only used **if there is no matching provider above at all.** If there is a `<SomeContext value={undefined}>` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the context value.
1387
+
Note that the [default value from your `createContext(defaultValue)` call](#specifying-a-fallback-default-value) is only used **if there is no matching provider above at all.** If there is a `<SomeContext value={undefined}>` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the Context value.
0 commit comments