-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Add docs for new Context API #665
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
566406e
0780f72
a5022da
fe3d0a4
808e5bd
de22379
291b2fd
6aa1995
7c6688c
b49f99b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,35 +4,71 @@ title: Context | |
permalink: docs/context.html | ||
--- | ||
|
||
> Note: | ||
> | ||
> `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types) to define `contextTypes`. | ||
> | ||
>We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) to automate the conversion. | ||
Context provides a way to pass data through the component tree without having to pass props down manually at every level. | ||
|
||
## Using Context | ||
|
||
Here is an example illustrating how you might inject a "theme" using context: | ||
|
||
`embed:context/theme-example.js` | ||
|
||
### API | ||
|
||
#### `React.createContext` | ||
|
||
```js | ||
const {Provider, Consumer} = React.createContext([default]); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why const {Provider, Consumer} = React.createContext(defaultValue); There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I was thinking [] indicated optional arguments. Replacing it with a text note is fine; it's not a real type signature or anything. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Gotcha. I don't think thats' what "[]" implies to me. 👍 |
||
``` | ||
|
||
Creates a `{ Provider, Consumer }` pair. | ||
|
||
Takes one argument, the default context that Consumers will receive when they don't have a matching Provider. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion:
|
||
|
||
|
||
#### `Provider` | ||
|
||
```js | ||
<Provider value={/* some value */}> | ||
``` | ||
|
||
With React, it's easy to track the flow of data through your React components. When you look at a component, you can see which props are being passed, which makes your apps easy to reason about. | ||
A React component that allows Consumers to subscribe to context changes. | ||
|
||
In some cases, you want to pass data through the component tree without having to pass the props down manually at every level. | ||
You can do this directly in React with the powerful "context" API. | ||
Takes one prop, `value`, which will be passed to the [render prop](/docs/render-props.html) of child Consumers for the matching context anywhere in the component tree. One Provider can be connected to many Consumers. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion:
|
||
|
||
#### `Consumer` | ||
|
||
```js | ||
<Consumer> | ||
{ value => { /* render something based on the context value */ } } | ||
</Consumer> | ||
``` | ||
|
||
A React component that subscribes to context changes. | ||
|
||
Takes a function as the `children` prop that receives the `value` prop of the matching Provider. This function will be called whenever the Provider's value is updated. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion:
|
||
|
||
> Note: | ||
> | ||
> A [new, safe version of context](https://github.com/reactjs/rfcs/blob/master/text/0002-new-version-of-context.md) is under development for the upcoming 16.3 release. | ||
> For more information about this pattern, see [render props](/docs/render-props.html). | ||
|
||
### Typical Usage | ||
|
||
`embed:context/theme-detailed-theme-context.js` | ||
|
||
## Why Not To Use Context | ||
`embed:context/theme-detailed-themed-button.js` | ||
|
||
The vast majority of applications do not need to use context. | ||
`embed:context/theme-detailed-app.js` | ||
|
||
If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React. | ||
|
||
If you aren't familiar with state management libraries like [Redux](https://github.com/reactjs/redux) or [MobX](https://github.com/mobxjs/mobx), don't use context. For many practical applications, these libraries and their React bindings are a good choice for managing state that is relevant to many components. It is far more likely that Redux is the right solution to your problem than that context is the right solution. | ||
## Experimental API (Deprecated in React 16.3) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe this could be broken out into its own "Legacy context" page (e.g. |
||
|
||
If you're still learning React, don't use context. There is usually a better way to implement functionality just using props and state. | ||
> The old experimental API is deprecated as of React 16.3. The API will be supported in all 16.x releases, but applications using it should migrate to the new API. | ||
|
||
If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes. | ||
The experimental API lacked a safe mechanism to update context. Version 16.3 introduced a new context API that is more efficient and supports both static type checking and deep updates. | ||
|
||
## How To Use Context | ||
### How To Use Context | ||
|
||
> This section documents a deprecated API | ||
|
||
Suppose you have a structure like: | ||
|
||
|
@@ -119,7 +155,15 @@ By adding `childContextTypes` and `getChildContext` to `MessageList` (the contex | |
|
||
If `contextTypes` is not defined, then `context` will be an empty object. | ||
|
||
## Parent-Child Coupling | ||
> Note: | ||
> | ||
> `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types) to define `contextTypes`. | ||
> | ||
> We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) to automate the conversion. | ||
|
||
### Parent-Child Coupling | ||
|
||
> This section documents a deprecated API | ||
|
||
Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://reacttraining.com/react-router): | ||
|
||
|
@@ -149,7 +193,9 @@ By passing down some information from the `Router` component, each `Link` and `R | |
|
||
Before you build components with an API similar to this, consider if there are cleaner alternatives. For example, you can pass entire React components as props if you'd like to. | ||
|
||
## Referencing Context in Lifecycle Methods | ||
### Referencing Context in Lifecycle Methods | ||
|
||
> This section documents a deprecated API | ||
|
||
If `contextTypes` is defined within a component, the following [lifecycle methods](/docs/react-component.html#the-component-lifecycle) will receive an additional parameter, the `context` object: | ||
|
||
|
@@ -162,7 +208,9 @@ If `contextTypes` is defined within a component, the following [lifecycle method | |
> | ||
> As of React 16, `componentDidUpdate` no longer receives `prevContext`. | ||
|
||
## Referencing Context in Stateless Functional Components | ||
### Referencing Context in Stateless Functional Components | ||
|
||
> This section documents a deprecated API | ||
|
||
Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows a `Button` component written as a stateless functional component. | ||
|
||
|
@@ -177,7 +225,9 @@ const Button = ({children}, context) => | |
Button.contextTypes = {color: PropTypes.string}; | ||
``` | ||
|
||
## Updating Context | ||
### Updating Context | ||
|
||
> This section documents a deprecated API | ||
|
||
Don't do it. | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import ThemeContext from './theme-context'; | ||
import ThemedButton from './button'; | ||
|
||
class App extends React.Component { | ||
state = { | ||
theme: { | ||
highlight: 'blue', | ||
accent: 'purple', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: It's also a little weird that we have a default value and There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What's a good application use case for the default value? The RFC example just says "to ensure type correctness". There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That's a good observation. I wasn't considering the type-correctness angle. 👍 I was thinking it would be nice for the docs to highlight, in one of the examples, that the default value gets passed to a Consumer if there is no Provider ancestor. |
||
}, | ||
}; | ||
|
||
changeHighlightColor = () => { | ||
const colors = ['red', 'blue', 'green']; | ||
const randomColor = | ||
colors[Math.floor(Math.random() * 3)]; | ||
this.setState({ | ||
theme: { | ||
...this.state.theme, | ||
highlight: randomColor, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not a big fan of this randomization. Maybe we could simplify this a bit with a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I was hoping to show something with a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah, I see. An object value or something seems fine. I just think the randomness maybe detracts from the example some. |
||
}, | ||
}); | ||
}; | ||
|
||
render() { | ||
return ( | ||
<ThemeContext.Provider value={this.state.theme}> | ||
<div> | ||
<ThemedButton onClick={this.changeHighlightColor}> | ||
Change Theme | ||
</ThemedButton> | ||
</div> | ||
</ThemeContext.Provider> | ||
); | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like the changes to the theme example as well. |
||
|
||
ReactDOM.render(<App />, document.root); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
const defaultTheme = {highlight: 'blue', accent: 'purple'}; | ||
|
||
const ThemeContext = React.createContext(defaultTheme); | ||
|
||
export default ThemeContext; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import ThemeContext from './theme-context'; | ||
|
||
class ThemedButton extends React.Component { | ||
render() { | ||
return ( | ||
<ThemeContext.Consumer> | ||
{theme => ( | ||
<button | ||
{...this.props} | ||
style={{backgroundColor: theme.highlight}} | ||
/> | ||
)} | ||
</ThemeContext.Consumer> | ||
); | ||
} | ||
} | ||
|
||
export default ThemedButton; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
const defaultTheme = 'light'; | ||
// highlight-next-line | ||
const ThemeContext = React.createContext(defaultTheme); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: Maybe get rid of // Initial context with a default value of "light" (theme)
const ThemeContext = React.createContext('light'); |
||
|
||
class ThemeProvider extends React.Component { | ||
state = {theme: 'light'}; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe show a different value than the default? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Actually copied this from the blog post: https://github.com/reactjs/reactjs.org/pull/587/files#diff-551ec185a5d5f7818d2b02fbbf901c28 I'll simplify this one since the dynamic example covers stateful providers. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 😆 That's fair! |
||
|
||
render() { | ||
// highlight-range{2-4} | ||
return ( | ||
<ThemeContext.Provider value={this.state.theme}> | ||
{this.props.children} | ||
</ThemeContext.Provider> | ||
); | ||
} | ||
} | ||
|
||
class ThemedButton extends React.Component { | ||
render() { | ||
//highlight-range{2-4} | ||
return ( | ||
<ThemeContext.Consumer> | ||
{theme => <Button theme={theme} />} | ||
</ThemeContext.Consumer> | ||
); | ||
} | ||
} | ||
|
||
class App extends React.Component { | ||
// highlight-range{3} | ||
// highlight-range{5} | ||
// highlight-range{7} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. // highlight-range{3,5,7} There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah, I was looking for docs on that |
||
render() { | ||
return ( | ||
<ThemeProvider> | ||
<SomeComponent> | ||
<ThemedButton /> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wonder if we should omit |
||
</SomeComponent> | ||
</ThemeProvider> | ||
); | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I prefer the introductory sequence from the old "How to Use Context" section more because of how it setup the problem. "Let's say you have this code and you want to do X. Here's how you could use the context API to do this." rather than "Here's a code snippet"
I would also suggesting putting this down under the "Typical Usage" header. I think the API should be first on this page.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's confusing how the old example leads with a large codeblock illustrating non-context APIs. Maybe we can invert the order to highlight the context way before the prop-drilling way?
Moving the API section to the top makes sense.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we could maybe make the initial code block shorter, but I think it's useful to present APIs in the form of "Here is a scenario. How would you solve it? You can solve it using this API."