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.
214 lines
6.8 KiB
214 lines
6.8 KiB
9 years ago
|
---
|
||
|
id: context
|
||
|
title: Context
|
||
9 years ago
|
permalink: docs/context.html
|
||
9 years ago
|
---
|
||
|
|
||
8 years ago
|
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.
|
||
9 years ago
|
|
||
8 years ago
|
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.
|
||
9 years ago
|
|
||
8 years ago
|
## Why Not To Use Context
|
||
9 years ago
|
|
||
8 years ago
|
The vast majority of applications do not need to use context.
|
||
|
|
||
|
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.
|
||
|
|
||
|
If you aren't an experienced React developer, don't use context. There is usually a better way to implement functionality just using props and state.
|
||
|
|
||
|
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.
|
||
|
|
||
|
## How To Use Context
|
||
9 years ago
|
|
||
|
Suppose you have a structure like:
|
||
|
|
||
|
```javascript
|
||
9 years ago
|
class Button extends React.Component {
|
||
|
render() {
|
||
9 years ago
|
return (
|
||
|
<button style={{'{{'}}background: this.props.color}}>
|
||
|
{this.props.children}
|
||
|
</button>
|
||
|
);
|
||
|
}
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
9 years ago
|
class Message extends React.Component {
|
||
|
render() {
|
||
9 years ago
|
return (
|
||
|
<div>
|
||
|
{this.props.text} <Button color={this.props.color}>Delete</Button>
|
||
|
</div>
|
||
|
);
|
||
|
}
|
||
9 years ago
|
}
|
||
|
|
||
|
class MessageList extends React.Component {
|
||
|
render() {
|
||
|
const color = "purple";
|
||
|
const children = this.props.messages.map((message) =>
|
||
|
<Message text={message.text} color={color} />
|
||
|
);
|
||
9 years ago
|
return <div>{children}</div>;
|
||
9 years ago
|
}
|
||
9 years ago
|
}
|
||
9 years ago
|
```
|
||
|
|
||
8 years ago
|
In this example, we manually thread through a `color` prop in order to style the `Button` and `Message` components appropriately. Using context, we can pass this through the tree automatically:
|
||
9 years ago
|
|
||
9 years ago
|
```javascript{4,11-13,19,26-28,38-40}
|
||
|
class Button extends React.Component {
|
||
|
render() {
|
||
9 years ago
|
return (
|
||
|
<button style={{'{{'}}background: this.context.color}}>
|
||
|
{this.props.children}
|
||
|
</button>
|
||
|
);
|
||
|
}
|
||
9 years ago
|
}
|
||
|
|
||
|
Button.contextTypes = {
|
||
|
color: React.PropTypes.string
|
||
|
};
|
||
9 years ago
|
|
||
9 years ago
|
class Message extends React.Component {
|
||
|
render() {
|
||
9 years ago
|
return (
|
||
|
<div>
|
||
|
{this.props.text} <Button>Delete</Button>
|
||
|
</div>
|
||
|
);
|
||
|
}
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
9 years ago
|
class MessageList extends React.Component {
|
||
|
getChildContext() {
|
||
9 years ago
|
return {color: "purple"};
|
||
9 years ago
|
}
|
||
|
|
||
|
render() {
|
||
|
const children = this.props.messages.map((message) =>
|
||
|
<Message text={message.text} />
|
||
|
);
|
||
9 years ago
|
return <div>{children}</div>;
|
||
|
}
|
||
9 years ago
|
}
|
||
|
|
||
|
MessageList.childContextTypes = {
|
||
|
color: React.PropTypes.string
|
||
|
};
|
||
9 years ago
|
```
|
||
|
|
||
|
By adding `childContextTypes` and `getChildContext` to `MessageList` (the context provider), React passes the information down automatically and any component in the subtree (in this case, `Button`) can access it by defining `contextTypes`.
|
||
|
|
||
9 years ago
|
If `contextTypes` is not defined, then `context` will be an empty object.
|
||
9 years ago
|
|
||
8 years ago
|
## Parent-Child Coupling
|
||
9 years ago
|
|
||
8 years ago
|
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://react-router.now.sh/basic):
|
||
9 years ago
|
|
||
|
```javascript
|
||
8 years ago
|
const BasicExample = () => (
|
||
|
<Router>
|
||
|
<div>
|
||
|
<ul>
|
||
|
<li><Link to="/">Home</Link></li>
|
||
|
<li><Link to="/about">About</Link></li>
|
||
|
<li><Link to="/topics">Topics</Link></li>
|
||
|
</ul>
|
||
|
|
||
|
<hr/>
|
||
|
|
||
|
<Match exactly pattern="/" component={Home} />
|
||
|
<Match pattern="/about" component={About} />
|
||
|
<Match pattern="/topics" component={Topics} />
|
||
|
</div>
|
||
|
</Router>
|
||
|
)
|
||
9 years ago
|
```
|
||
|
|
||
8 years ago
|
By passing down some information from the `Router` component, each `Link` and `Match` can communicate back to the containing `Router`.
|
||
9 years ago
|
|
||
8 years ago
|
Before you build components with an API similar to this, consider if there are cleaner alternatives. For example, you can pass entire React component as props if you'd like to.
|
||
9 years ago
|
|
||
8 years ago
|
## Referencing Context in Lifecycle Methods
|
||
9 years ago
|
|
||
|
If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object:
|
||
|
|
||
|
```javascript
|
||
|
void componentWillReceiveProps(
|
||
|
object nextProps, object nextContext
|
||
|
)
|
||
|
|
||
|
boolean shouldComponentUpdate(
|
||
|
object nextProps, object nextState, object nextContext
|
||
|
)
|
||
|
|
||
|
void componentWillUpdate(
|
||
|
object nextProps, object nextState, object nextContext
|
||
|
)
|
||
|
|
||
|
void componentDidUpdate(
|
||
|
object prevProps, object prevState, object prevContext
|
||
|
)
|
||
|
```
|
||
|
|
||
8 years ago
|
## Referencing Context in Stateless Functional Components
|
||
9 years ago
|
|
||
8 years ago
|
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.
|
||
9 years ago
|
|
||
|
```javascript
|
||
9 years ago
|
const Button = ({children}, context) =>
|
||
|
<button style={{'{{'}}background: context.color}}>
|
||
|
{children}
|
||
|
</button>;
|
||
|
|
||
9 years ago
|
Button.contextTypes = {color: React.PropTypes.string};
|
||
|
```
|
||
|
|
||
8 years ago
|
## Updating Context
|
||
|
|
||
|
Don't do it.
|
||
|
|
||
|
React has an API to update context, but it is fundamentally broken and you should not use it.
|
||
9 years ago
|
|
||
|
The `getChildContext` function will be called when the state or props changes. In order to update data in the context, trigger a local state update with `this.setState`. This will trigger a new context and changes will be received by the children.
|
||
|
|
||
|
```javascript
|
||
9 years ago
|
class MediaQuery extends React.Component {
|
||
|
constructor(props) {
|
||
|
super(props);
|
||
|
this.state = {type:'desktop'};
|
||
|
}
|
||
|
|
||
|
getChildContext() {
|
||
9 years ago
|
return {type: this.state.type};
|
||
9 years ago
|
}
|
||
|
|
||
|
componentDidMount() {
|
||
|
const checkMediaQuery = () => {
|
||
|
const type = window.matchMedia("(min-width: 1025px)").matches ? 'desktop' : 'mobile';
|
||
|
if (type !== this.state.type) {
|
||
|
this.setState({type});
|
||
9 years ago
|
}
|
||
|
};
|
||
9 years ago
|
|
||
9 years ago
|
window.addEventListener('resize', checkMediaQuery);
|
||
|
checkMediaQuery();
|
||
9 years ago
|
}
|
||
|
|
||
|
render() {
|
||
9 years ago
|
return this.props.children;
|
||
|
}
|
||
9 years ago
|
}
|
||
|
|
||
|
MediaQuery.childContextTypes = {
|
||
|
type: React.PropTypes.string
|
||
|
};
|
||
9 years ago
|
```
|
||
|
|
||
8 years ago
|
The problem is, if a context value provided by component changes, descendants that use that value won't update if an intermediate parent returns `false` from `shouldComponentUpdate`. This is totally out of control of the components using context, so there's basically no way to reliably update the context. [This blog post](https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076) has a good explanation of why this is a problem and how you might get around it.
|