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 />
      </ThemeContext.Provider>
    );
  }
}

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

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.

Original Content ,

2 Responses to React’s new context (React 16.3.0)

  1. Pingback: The exciting future of React | Bram.us

  2. Pingback: React v16.3.0: New Lifecycle Events and Context API | Bram.us

Leave a Reply

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.