React Context API: What Is It And How Does It Work?

March 07, 2023
React Context API What is it and How Does it Work



In component-based frameworks, the need to pass data between components is ever-present. The transfer usually occurs from parent to child, yet the opposite is not uncommon. In this process, some have to hold data they don’t need for the sake of the system.

That becomes an issue for props always in demand by more than one component, like UI themes, locale preference, and language settings. Here, react context API, an advanced component structure, helps as it enables data to move from one component to another without the need to touch every level.

react dev jobs

In this article, we’ll cover react context API and describe what it is, how it works, and how to use it.

React Context API Defined

By definition, it is a component structure through which we can transfer data seamlessly across different levels. Designed by the React Framework, it functions to resolve issues related to prop drilling.

In other words, context API is a React app designed to create global variables, passable to any level within an application system. It presents us with a better way to move props than drilling them. Best said it is a functionality that simplifies Redux-based state management.

The context API is not new and has always been present within React, yet for experimental purposes only. It officially launched to improve stability with version 16.3 and quickly rose to popularity.

How Does React Context API Work?

The react context API works mainly through two components; a provider and a consumer. The former has the store, acts as a parent, and transfers the state to a child component per need. While the latter, as the word defines, is a consumer and consumes it.

Moreover, the context API works via a central store packed with data ever-ready for transfer. You can insert the store into any component to cut the intermediary, remove the hassle, and speed up development.

To achieve this, all you need to do is create a provider and a consumer. You can make context API works in three steps.

Step 1 – Context Formulation

The first step is to build the context through which we can create providers and consumers later.

import React from 'react'; 
// this is the equivalent to the createStore method of Redux 
// https://redux.js.org/api/createstore 
const MyContext = React.createContext(); 
export default MyContext;

Step 2 – Provider Formulation

Now it is time to create a provider. Let’s name it TheProvider. In it, we state some values shared via value prop. For example, let’s share this.state.phone and a few methods to manipulate the state further.

Import MyContext from './MyContext'; 
class TheProvider extends Component { 
           state = { 
                phones: { 
                   phones001: { name: 'Nokia', price: 100 },
                   phones002: { name: 'Samsung', price: 150 }, 
                   phones003: { name: 'Apple', price: 200 }
               } 
           }; 
        render() { 
           return ( 
               <TheContext.Provider 
                   value={{ 
                       phones: this.state.phones,
                       incrementPrice: selectedID => { 
                          const phones = Object.assign({}, this.state.phones);
                          phones[selectedID].price = phones[selectedID].price + 1;
                          this.setState({ 
                               phones
                          });
                    },
                   decrementPrice: selectedID => { 
                         const phones = Object.assign({}, this.state.phones);
                         phones[selectedID].price = phones[selectedID].price - 1;
                         this.setState({ 
                              cars 
                         }); 
                    } 
              }}
         > 
              {this.props.children}
         </TheContext.Provider>
       ); 
   } 
}

Step 3 – Consumer Formulation

Forming a consumer requires recreating context and wrapping the component with it. Once done, the rest is easy. Use context like you use props. Remember, context is a repository with values stored in the central store.

const phones = () => (

    <TheContext.Consumer>

        {context => (

            <Fragment>

                <h4>phones:</h4>

                {Object.keys(context.phones).map(phoneID => (

                    <Car

                        key={phoneID}

                        name={context.phones[phoneID].name}

                        price={context.phones[phoneID].price}

                        incrementPrice={() => context.incrementPrice(phoneID)}

                        decrementPrice={() => context.decrementPrice(phoneID)}

                    />

                ))}

            </Fragment>

        )}

    </TheContext.Consumer>

);

Will The React Context API Replace Redux?

Redux’s best functionality was its ability to create and function via a central store and do much the same. The context API has the feature embedded in its core.

In addition, the ease of access you get with the context API and its ability to define unlinked stores (contexts) doesn’t help Redux’s case. Thus, it won’t be wrong to say there exists a strong possibility the context will make Redux obsolete shortly.

Remember, Redux requires third-party libraries to do what the context API does independently. Even if react context API didn’t make Redux obsolete, it will definitely end developers’ overreliance on the concept as now a better, simpler, and faster way to transfer data from one component to another exists.

Also Read: What Is The useState In React: A Complete Guide?

react jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US