Created
December 6, 2014 02:21
-
-
Save captainill/c2deb9ad4b935bab6006 to your computer and use it in GitHub Desktop.
notes on React Context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Contexts | |
Summary: | |
adds `this.context` which you can think of as implicit props, which are passed automatically down the //ownership// hierarchy. | |
Contexts should be used sparingly, since they essentially allow components to communicate with descendants (in the ownership sense, not parenthood sense), which is not usually a good idea. You probably would only use contexts in places where you'd normally use a global, but contexts allow you to override them for certain view subtrees which you can't do with globals. | |
The context starts out `null`: | |
var RootComponent = React.createClass({ | |
render: function() { | |
// this.context === null | |
} | |
}); | |
You should **never** mutate the context directly, just like props and state. | |
You can change the context of your children (the ones you own, not `this.props.children` or via other props) using the new `withContext` method on `React`: | |
var RootComponent = React.createClass({ | |
render: function() { | |
// this.context === null | |
var children = React.withContext({foo: 'a', bar: 'b'}, () => ( | |
// In ChildComponent#render, this.context === {foo: 'a', bar: 'b'} | |
<ChildComponent /> | |
)); | |
// this.context === null | |
} | |
}); | |
Contexts are merged, so a component can override its owner's context **for its children**: | |
var ChildComponent = React.createClass({ | |
render: function() { | |
// this.context === {foo: 'a', bar: 'b'} (for the caller above) | |
var children = React.withContext({foo: 'c'},() => ( | |
// In GrandchildComponent#render, | |
// this.context === {foo: 'c', bar: 'b'} | |
<GrandchildComponent /> | |
)); | |
// this.context === {foo: 'a', bar: 'b'} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment