Context api in React.js


The React context api is safe to use in production with the version 16.3 or latest. The reason for adding context api is to avoid the passing of props if there is a chain of children components.

Without the use of context api, we have to pass the props through all the intermediate components. The other alternative solution is to use third party library such as Redux for maintaining a central store.

Understanding the passing of props problem

App.js → props for books → BookList.js → passing the books as props again → Book.js

With the increase in number of children components, the chain of passing the props goes on.

With context api, react provides a provider consumer approach to solve this issue.

Creating the context:
BaseContext.js
import React from 'react';
// this is the same to the createStore method of Redux
const BaseContext = React.createContext();
export default BaseContext;

Create the provider

import BaseContext from './BaseContext';
class BookProvider extends Component {
   state = {
      books: {
         book1: { name: 'React', price: 500 },
         book2: { name: 'Angular', price: 450 }
      }
   };
   render() {
      return (
         <BaseContext.Provider
            value={{
               books: this.state.books,
               incrementPrice: selectedID => {
                  const books = Object.assign({}, this.state.books);
                  books[selectedID].price =books[selectedID].price + 1;
                  this.setState({
                     books
                  });
               },
               decrementPrice: selectedID => {
                  const books = Object.assign({}, this.state.books);
                  books[selectedID].price =books[selectedID].price - 1;
                  this.setState({
                     books
                  });
               }
            }}
         >
         {this.props.children}
         </BaseContext.Provider>
      );
   }
}

App.js

class App extends Component {
   render() {
      return (
         <BookProvider>
            <div className="App">
               <header className="App-header">
                  <h1 className="App-title">Welcome to my book store</h1>
               </header>
               <ProductBookList />
            </div>
         </BookProvider>
      );
   }
}

In the children component, we can use the consumer −

const Books = () => (
   <BaseContext.Consumer>
      {context => (
         <Fragment>
            <h4>Books:</h4>
            {Object.keys(context.books).map(bookID => (
               <Car
                  key={bookID}
                  name={context.books[bookID].name}
                  price={context.books[bookID].price}
                  incrementPrice={() =>context.incrementPrice(bookID)}
                  decrementPrice={() =>context.decrementPrice(bookID)}
               />
            ))}
         </Fragment>
      )}
   </BaseContext.Consumer>
);

With the use of context api we can avoid the props drilling in React children components.

Updated on: 04-Sep-2019

733 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements