Context

Context passes data through the component tree without passing props manually down every level.

A context is just a wrapper component (provider) with a default and current value. Way down the tree a child component (consumer) references a prop named after that context.

The simplest example

The theme will be “dark”.

// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');

class App extends React.Component {
    render() {
        // Use a Provider to pass the current theme to the tree below.
        // Any component can read it, no matter how deep it is.
        // In this example, we're passing "dark" as the current value.
        return (
            <ThemeContext.Provider value="dark">
                <Toolbar />
            </ThemeContext.Provider>
        );
    }
}
// A component in the middle doesn't have to pass the theme down explicitly anymore.
const Toolbar = props => (
    <div>
        <ThemedButton />
    </div>
);
// Assign a contextType to read the current theme context.
// React will find the closest "ThemeContext.Provider" above and use its value.
class ThemedButton extends React.Component {
    static contextType = ThemeContext;

    render() {
        return <Button theme={this.context} />;
    }
}

Articles

Wes Bos — React Context
16 minutes. Video demo of the context API.