React’s new context (React 16.3.0)

One of the new things in React 16.3.0 is a new context API:

Typically, data in a React application is passed top-down (parent to child) via props. But sometimes it’s useful to pass values through multiple levels of abstraction without involving each intermediate. Examples include a locale, or a UI theme.

Context in React provides a mechanism for a child component to access a value in an ancestor component. From now on we’ll refer to the ancestor as the provider and the child as the consumer.

Below is an example on how to use it. Create a context first, and then create a Provider along with one (or more) Consumer(s) that will be able to read the data from the Provider using its own context prop.

import React from 'react';
import {render} from 'react-dom';

const styles = {
  dark: {
    backgroundColor: 'black',
    color: 'white',
  light: {
    backgroundColor: 'white',
    color: 'black',

// 1. Create a context
const ThemeContext = React.createContext();

// 2. Our app contains a provider for ThemeContext.
// Anything we store into the ThemeContext will be accessible to a consumer
class App extends React.Component {
  state = {
    theme: 'light'

  toggleTheme = () => {
    this.setState(({ theme }) => ({
      theme: theme === 'light' ? 'dark' : 'light',

  render() {
    return (
      <ThemeContext.Provider value={this.state}>
        <button onClick={this.toggleTheme}>toggle theme</button>
        <ThemableDiv />

// 3. A consumer with access to the data contained in ThemeContext
class ThemableDiv extends React.PureComponent {
  render() {
        {context => <div style={styles[context.theme]}>{context.theme}</div>}

render(<App />, document.getElementById('root'));

In case you want to play with the code:

Note: The example is based on an example by Kent C. Dodds.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

About the author

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation


Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.