With React 16.3 recently released I thought it was time to take a look at the new context API. The new context API does what it says on the tin - it allows components to get data from a context rather than from props. It prevents having to pass props down through child component through child component … i.e. “prop drilling”.

Prop drilling v context API

So, let’s give this try for allowing a couple of components to consume data about a tenant in a multi-tenant app. The first child component will show the name of the tenant. The second child component will show a form capturing a name and age. Whether the age is captured depends on a promptForAge flag in the tenant.

Prop drilling v context API

Container component

The shell of our container component is below. It gets the tenant data from a web service and puts it in its state. We are referencing child components Title and ContactForm but we aren’t using the new context API yet.

class App extends Component {
  state = {
    tenant: null
  }

  componentDidMount() {
    fetch("http://localhost:21246/api/tenant")
      .then((response) => {
        return response.json();
      })
      .then(data => {
        this.setState({ tenant: data });
      }).catch(error => {
        console.log(error);
      });
  }
  render() {
    const {tenant} = this.state;
    return (
      {tenant &&
        <div className="container">
          <Title />
          <ContactForm />
        </div>
      }
    );
  }
}

Let’s create our context. We’ll call it TenantContext.

#react

Playing with the Context API in React 16.3
1.35 GEEK