You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

229 lines
9.7 KiB

---
id: context
title: Context
Upgrade to Jekyll 3 Full list of changes is at https://jekyllrb.com/docs/upgrading/2-to-3/. The tl;dr of it is: - Relative permalinks were removed, so all the files in the `docs` subdirectory need their permalink to be prefixed with `docs/` - `post` and `page` types were renamed to `posts` and `pages` respectively - `jekyll-paginate`, `pygments` and `redcarpet` are all now optional, so I needed to explicitly add it to the Gemfile. Jekyll now uses `rouge` rather than `pygments` for syntax highlighting, but rouge does not support highlighting individual lines (`hl_lines`) so we need to continue using Pygments. - Layout metadata (eg. `sectionid`) is now on a `layout` variable rather than `page` Tested the following pages and confirmed that they all work: - "Docs" link (getting started page): http://127.0.0.1:4000/react/docs/getting-started.html - Downloads: http://127.0.0.1:4000/react/downloads.html - Tutorial: http://127.0.0.1:4000/react/docs/tutorial.html - A few pages under the "docs" subdirectory, to confirm they're working properly: - http://127.0.0.1:4000/react/docs/addons.html - http://127.0.0.1:4000/react/docs/why-react.html - http://127.0.0.1:4000/react/docs/create-fragment.html - A few tips: - http://127.0.0.1:4000/react/tips/false-in-jsx.html - http://127.0.0.1:4000/react/tips/style-props-value-px.html - Non-English versions of the page: - http://127.0.0.1:4000/react/docs/getting-started-it-IT.html - http://127.0.0.1:4000/react/docs/getting-started-ja-JP.html
9 years ago
permalink: docs/context.html
---
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
- [When to Use Context](#when-to-use-context)
- [Before You Use Context](#before-you-use-context)
- [API](#api)
- [React.createContext](#reactcreatecontext)
- [Provider](#provider)
- [Consumer](#consumer)
- [Examples](#examples)
- [Dynamic Context](#dynamic-context)
- [Updating Context from a Nested Component](#updating-context-from-a-nested-component)
- [Consuming Multiple Contexts](#consuming-multiple-contexts)
- [Accessing Context in Lifecycle Methods](#accessing-context-in-lifecycle-methods)
- [Consuming Context with a HOC](#consuming-context-with-a-hoc)
- [Forwarding Refs to Context Consumers](#forwarding-refs-to-context-consumers)
- [Caveats](#caveats)
- [Legacy API](#legacy-api)
## When to Use Context
Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a "theme" prop in order to style the Button component:
`embed:context/motivation-problem.js`
Using context, we can avoid passing props through intermediate elements:
`embed:context/motivation-solution.js`
## Before You Use Context
Context is primarily used when some data needs to be accessible by *many* components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.
**If you only want to avoid passing some props through many levels, [component composition](/docs/composition-vs-inheritance.html) is often a simpler solution than context.**
7 years ago
For example, consider a `Page` component that passes a `user` prop several levels down so that a deeply nested `Avatar` component can read it:
```js
7 years ago
<Page user={user} />
// ... which renders ...
<PageLayout user={user} />
// ... which renders ...
<NavigationBar user={user} />
// ... which renders ...
<Avatar user={user} />
```
7 years ago
It might feel redundant to pass down the `user` prop through many levels if in the end only the `Avatar` component really needs it. It's also annoying that whenever the `Avatar` component needs more props from the top, you have to add them at all the intermediate levels too.
7 years ago
To solve this issue **without context**, change `PageLayout` and `NavigationBar` to [accept a `children` prop](/docs/composition-vs-inheritance.html#containment). Then the `Page` component could pass `<Avatar user={user} />` down as a child, and neither of the components below would need to know about the `user` prop:
```js
7 years ago
function Page(props) {
const user = props.user;
return (
<PageLayout>
<NavigationBar>
7 years ago
<Avatar user={user} />
</NavigationBar>
</PageLayout>
);
}
```
You're not limited to a single child for a component. You may pass multiple children, or even have multiple separate "slots" for children, [as documented here](/docs/composition-vs-inheritance.html#containment):
```js
7 years ago
function Page(props) {
const user = props.user;
const content = <Feed user={user} />;
const topBar = (
<NavigationBar>
7 years ago
<Avatar user={user} />
</NavigationBar>
);
return (
<PageLayout
topBar={topBar}
content={content}
/>
);
}
```
This pattern is sufficient for many cases when you need to decouple a child from its immediate parents. You can take it even further with [render props](/docs/render-props.html) if the child needs to communicate with the parent before rendering.
7 years ago
However, sometimes the same data needs to be accessible by many components in the tree, and at different nesting levels. Context lets you "broadcast" such data, and changes to it, to all components below. Common examples where using context might be simpler than the alternatives include managing the current locale, theme, or a data cache.
## API
### `React.createContext`
```js
const {Provider, Consumer} = React.createContext(defaultValue);
```
Creates a `{ Provider, Consumer }` pair. When React renders a context `Consumer`, it will read the current context value from the closest matching `Provider` above it in the tree.
The `defaultValue` argument is **only** used by a Consumer when it does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing `undefined` as a Provider value does not cause Consumers to use `defaultValue`.
### `Provider`
```js
<Provider value={/* some value */}>
```
All doc updates forv15.5 (#9359) * `react-addons-test-utils` -&gt; `react-dom/test-utils` Updating all references and docs on the `React.addons.TestUtils` and the shallow renderer to refer to the correct targets. Instead of: ``` const React = require(&#39;react&#39;); // ... React.addons.Testutils // or const ReactTestUtils = require(&#39;react-addons-test-utils&#39;); ``` we now show: ``` const ReactTestUtils = require(&#39;react-dom/test-utils&#39;); ``` And for shallow renderer, instead of: ``` const shallowRenderer = TestUtils.createRenderer(); ``` we now show: ``` const shallowRenderer = require(&#39;react-test-renderer/shallow&#39;); ``` * Update the &#39;prev&#39; and &#39;next&#39; attributes of &#39;add-ons&#39; docs These flags are used to set arrow links to easily navigate through the documents. They were wrong or missing in some of the &#39;add-ons&#39; pages and this bothered me when manually testing the updates from the previous commit. * Update syntax for instantiating shallow renderer Missed this when updating the docs for the changes to shallow-renderer in React 15.5. * Fix pointers in addons docs Thanks @bvaughn for catching this * Make example of shallow renderer more consistent We should show using the same variable names between code samples. * Make names in example even more consistent We should use the same variable name for the same thing across examples. `renderer` -&gt; `shallowRenderer`. * Update docs to deprecate React&lt;CSS&gt;TransitionGroup - removes link to the docs about `ReactCSSTransitionGroup` and `ReactTransitionGroup` from the main navigation - updates &#39;prev&#39; and &#39;next&#39; pointers to skip this page - adds deprecation warning to the top of the page - remove references to these modules from the packages README - updates &#39;add-ons&#39; main page to list this as a deprecated add-on * Update `React.createClass` to `createReactClass` in the docs The `React.createClass` method is being deprecated in favor of `createReactClass`. * Remove &#39;React.createClass&#39; from top level API docs It no longer makes sense to have a section for the &#39;createClass&#39; method in this page, since it won&#39;t be available as a top level method on &#39;React&#39;. I initially was going to pull the section about &#39;createClass&#39; into a separate page to add under &#39;addons&#39; but it was short and duplicative of the &#39;react-without-es6&#39; docs. So I just linked to those. * Remove *most* `React.PropTypes` from the docs I am doing the docs for `context` in a separate commit because that case was a bit less clear-cut. We will no longer support `React.PropTypes` as a built-in feature of React, and instead should direct folks to use the `PropTypes` project that stands alone. Rather than retaining the `React.PropTypes` examples and just revamping them to show the use of the stand-alone `PropTypes` library with React, it makes more sense to direct people to that project and reduce the perceived API area and complexity of React core. The proper place to document `PropTypes` is in the README or docs of that project, not in React docs. * Update `context` docs to not use `React.PropTypes` We use `React.PropTypes` to define the `contextType` for the `context` feature of React. It&#39;s unclear how this will work once `React.PropTypes` is replaced by the external `PropTypes` library. Some options; a) Deprecate `context`, either in v16 or shortly after. Seems reasonable based on the intense warnings against using context that we have in the docs - https://facebook.github.io/react/docs/context.html#why-not-to-use-context **Except** that probably some widely used libraries depend on it, like `React-Router`. b) Expect users will use external `PropTypes` library when defining `contextTypes` and just don&#39;t do our `checkReactTypeSpec` against them any more in v16. c) Stop masking context and pass the whole context unmasked everywhere. Worst option, do not recommend. I went with `b` and assume that, for now, we will get users to use the external `PropTypes` when defining context. I will update this PR if we want a different approach. * Remove &#39;addons&#39; items from left nav, and deprecate &#39;addons&#39; doc page The plan: [X] Remove links to &#39;addons&#39; items from main navigation [X] Add deprecation notices where appropriate, and update syntax to show using the separate modules. [ ] Update other references to &#39;React.addons&#39; in docs. Coming in next commit. --- blocked but coming in future PRs [ ] Link to a blog post describing the new locations of add-ons in the deprecation notice on the &#39;/docs/addons.html&#39; page. Blocked until we actually publish that blog post. [ ] Move the docs for each add-on to the actual github repo where it now lives. [ ] Redirect the old add-ons doc permalinks to the docs in the separate github repos for those modules. [ ] Remove the old add-ons doc markdown files from React core docs. * Remove references to `React.addons` from docs Just misc. places where we referenced the &#39;addons&#39; feature. All gone!
8 years ago
A React component that allows Consumers to subscribe to context changes.
Accepts a `value` prop to be passed to Consumers that are descendants of this Provider. One Provider can be connected to many Consumers. Providers can be nested to override values deeper within the tree.
### `Consumer`
```js
<Consumer>
{value => /* render something based on the context value */}
</Consumer>
```
A React component that subscribes to context changes.
7 years ago
Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). The function receives the current context value and returns a React node. The `value` argument passed to the function will be equal to the `value` prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the `value` argument will be equal to the `defaultValue` that was passed to `createContext()`.
> Note
>
> For more information about the 'function as a child' pattern, see [render props](/docs/render-props.html).
All Consumers that are descendants of a Provider will re-render whenever the Provider's `value` prop changes. The propagation from Provider to its descendant Consumers is not subject to the `shouldComponentUpdate` method, so the Consumer is updated even when an ancestor component bails out of the update.
Changes are determined by comparing the new and old values using the same algorithm as [`Object.is`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).
7 years ago
> Note
>
> The way changes are determined can cause some issues when passing objects as `value`: see [Caveats](#caveats).
## Examples
### Dynamic Context
A more complex example with dynamic values for the theme:
7 years ago
**theme-context.js**
`embed:context/theme-detailed-theme-context.js`
**themed-button.js**
`embed:context/theme-detailed-themed-button.js`
**app.js**
`embed:context/theme-detailed-app.js`
### Updating Context from a Nested Component
It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this case you can pass a function down through the context to allow consumers to update the context:
**theme-context.js**
`embed:context/updating-nested-context-context.js`
**theme-toggler-button.js**
`embed:context/updating-nested-context-theme-toggler-button.js`
**app.js**
`embed:context/updating-nested-context-app.js`
### Consuming Multiple Contexts
To keep context re-rendering fast, React needs to make each context consumer a separate node in the tree.
`embed:context/multiple-contexts.js`
7 years ago
If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.
### Accessing Context in Lifecycle Methods
Accessing values from context in lifecycle methods is a relatively common use case. Instead of adding context to every lifecycle method, you just need to pass it as a prop, and then work with it just like you'd normally work with a prop.
`embed:context/lifecycles.js`
### Consuming Context with a HOC
Some types of contexts are consumed by many components (e.g. theme or localization). It can be tedious to explicitly wrap each dependency with a `<Context.Consumer>` element. A [higher-order component](/docs/higher-order-components.html) can help with this.
For example, a button component might consume a theme context like so:
`embed:context/higher-order-component-before.js`
That's alright for a few components, but what if we wanted to use the theme context in a lot of places?
We could create a higher-order component called `withTheme`:
`embed:context/higher-order-component.js`
7 years ago
Now any component that depends on the theme context can easily subscribe to it using the `withTheme` function we've created:
`embed:context/higher-order-component-usage.js`
### Forwarding Refs to Context Consumers
One issue with the render prop API is that refs don't automatically get passed to wrapped elements. To get around this, use `React.forwardRef`:
**fancy-button.js**
`embed:context/forwarding-refs-fancy-button.js`
**app.js**
`embed:context/forwarding-refs-app.js`
## Caveats
Because context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider's parent re-renders. For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for `value`:
`embed:context/reference-caveats-problem.js`
To get around this, lift the value into the parent's state:
`embed:context/reference-caveats-solution.js`
## Legacy API
7 years ago
> Note
>
7 years ago
> React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in a future major React version. Read the [legacy context docs here](/docs/legacy-context.html).
7 years ago