Understanding React Context API

Posted on June 03, 2019


Data in React is passed from parent component to child component through props. This pattern of passing data through props works fine for a small application, but there will be a case when a certain props are required by many components, and this is where React's Context API come to help. An example can be UI theme of your application.

Let's learn Context API through a simple application. You can visit the codesandbox here.

As you can see in the sandbox, this React application renders a list of numbers or letters representing numbers. The parent component pass its state value through props, and the children components will render HTML elements according to this state value.

Now here is an example of the same application, but using React Context API instead of props.

In this application, A React context object is created using the React.CreateContext() function on line 4:

const MyContext = React.createContext();

The context object has two component properties: Provider and Consumer

The Provider component will be used as a parent component who hold values that is share-able to all Consumer components.

render() {
  return (
    <MyContext.Provider
      value={
        {
          state: this.state,
          updateState: () => this.toggleState()
        }
      }
    >
      <List />
      <List2 />
    </MyContext.Provider>
  );
}

Since Context in React is designed to share data that is considered "global", it is recommended to put the Provider component at the top level of your component hierarchy. Also note that Consumer component can only be used on the children of Provider component.

Now since <List /> and <List2 /> components are children of <MyContext.Provider /> component, you can use Consumer component inside them. Simply wrap all elements rendered by list components inside the Consumer component:

function List() {
  return (
    <MyContext.Consumer>
      {context => (
        <div>
          <ul>
            <li>{context.state.theme === "number" ? "1" : "one"}</li>
            <li>{context.state.theme === "number" ? "2" : "two"}</li>
            <li>{context.state.theme === "number" ? "3" : "three"}</li>
          </ul>

          <button onClick={context.updateState}>Change Theme</button>
        </div>
      )}
    </MyContext.Consumer>
  );
}

And you're good to go! This way, you won't need to pass props to children components. You can access context values by using Consumer component to all components that needs a certain value. For more information about the API, you can visit its documentation here

Share this:
LinkedIn
Reddit
WhatsApp

Get Free Guides