by Troy Rhinehart
https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076#.t01z8haut
Context is a very powerful feature in React, with lots of disclaimers around it. A bit like the forbidden fruit in paradise.
https://facebook.github.io/react/docs/context.html
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.
Context can also let you build an API where parents and children communicate.
https://facebook.github.io/react/docs/context.html
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 an experienced React developer, don't use context.
React has an API to update context, but it is fundamentally broken and you should not use it.
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.
Component.contextTypes = {
example: React.PropTypes.string
};If contextTypes is defined within a component, the following lifecycle methods will receive an additional parameter, the context object
constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)
class SetContextComponent extends React.Component {
static childContextTypes = {
example: React.PropTypes.string
};
getChildContext(){
return {
example: "Hello World"
};
}
render(){
return (
<div>
<Some>
<Thing>
<Deep>
<GetContextComponent/>
</Deep>
</Thing>
</Some>
</div>
);
}
}Class Component
class GetContextComponent extends React.Component {
static contextTypes = {
example: React.PropTypes.string
};
render(){
const { example } = this.context;
return <h1>{ example }</h1>
}
}function GetContextComponent(props, context) {
const { example } = context;
return <h1>{ example }</h1>
}
GetContextComponent.contextTypes = {
example: React.PropTypes.string
};Class Component
Stateless Functional Component