context

Context is an undocumented feature in React. I’ll talk about how it works in v0.13.


environment

Here’s an example of context. When I drop my son off at his grandparents, I remind him:

Grandma hates the word ‘shit.’ Be careful not to say it.

There’s a context in which my son uses more appropriate language for his environment. That context is grandma’s house. Does he say “shit?” Yup. Does he say it at grandma’s house? Nope.

warning

There’s a bunch of use cases where context is valid. The one where it’s not, is to save you typing... — Sebastian Markbåge at React.js Conf 2014

using context, today

context is implemented in three parts: getChildContext and childContextTypes, on the initiating component, and contextTypes on the child components.

getChildContext

In the component that initiates context, you’ll implement getChildContext:

class Chan extends React.Component {
getChildContext() {
return {
environment: "grandma's house"
}
}
}

childContextTypes

You’ll also use childContextTypes to set the context type for interested children.

Chan.childContextTypes = {
environment: React.PropTypes.string
};

contextTypes

Now our children may observe this context and behave accordingly.

class ChildChan extends React.Component {
render() {
if (this.context.environment === "grandma's house") {
return <span>poop</span>;
}
return <strong>shit</strong>;
}
}
ChildChan.contextTypes = {
environment: React.PropTypes.string
};

Don’t use context

As a general rule, don’t reach for context. I don’t use context much. I’ve used it for media queries and railsEnv.

Most of the time, you should use props.

I like to think of context the way I think of media queries. My app should run correctly without context. But context can be used to provide a more appropriate experience — “poop” vs “shit”.

Carry on, nerds.


Further reading: context unit tests

It should be noted that library code is a completely different thing. If your a library writer, context may be a good way of communicating library data between components without burdening end-developers.