Using context API in react

2 Min. Read
Oct 1, 2019

Introduction

Using Context API in React (Hooks and Classes) React Context API is a way to essentially create global variables that can be passed around in a React app. It provides easy way to access and modify the state of React Components.

Alternatives of Redux?

You don’t need to install any external library for state management anymore like REDUX. Everything you need is available in React. And it’s damn easy to use. This new API solves one major problem–prop drilling. Even if you’re not familiar with the term, if you’ve worked on a React.js app, it has probably happened to you. Prop drilling is the processing of getting data from component A to component Z by passing it through multiple layers of intermediary React components.

Implementation in easy 3 steps

1. Initialize the Context

First we need to create Context, which we can later use to create providers and consumers for the components.

1
2
3
4
5
6
   //context file
   import React from 'react';
   //creating context
   const MyContext = React.createContext({});
   export default MyContext;

2. Create the Provider

We can import the context and use it to create our provider, which we are calling MyProvider.In it, we initialize a state with some values, which you can share via value prop our provider component. All the child components inside Mycontext.Provider can able to use the states that we provide in the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   //provider file
   import React from 'react';
   import MyContext from './context';
   class MyProvider extends Component {
    state = {
        name: 'John Doe',
        age: 20
    };

    render() {
        return (
            //Provider of my context and passing values to child via props
            <MyContext.Provider
                value={{
                    name: this.state.name,
                    age: this.state.age
                }}
            >
              <Consumer />
            </MyContext.Provider>
        );
    }
 }

To make the provider accessible to other components, we need to wrap our app with it . While we’re at it, we can get rid of the state and the methods because they are now defined in MyProvider.

3. Create the Consumer

We’ll need to import the context again and wrap our component with it which injects the context argument in the component. Afterward, it’s pretty straight forward. You use context, the same way you would use props. It holds all the values we’ve shared in MyProvider, we just need to use it!

1
2
3
4
5
6
7
8
9
10
11
12
   //Consumer code, use of state on clild
   const Consumer = () => (
    <MyContext.Consumer>
        {context => (
            <React.Fragment>
                <h4>My Name is: {context.name}</h4>
                <h3>My Age is: {context.age}</h3>
            </React.Fragment>
        )}
    </MyContext.Consumer>
);

We can use context, the same way we use props. Context makes us easy to get rid of state on any components, which is wrapped by Provider.