paint-brush
How to use context API in Reactby@mandar-waghe
1,261 reads
1,261 reads

How to use context API in React

by Mandar WagheMay 27th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How to use context API in React is a component structure that is provided by React to manage the states for all the levels of your application. It will work the same way as redux and it helps you to replace redux or avoid using third party libraries. Let us see how to use it in our react application by creating a simple counter application to react. We will create a new context using the createContext() method of React. We have to define our context and we just have to pass the values of context through the provider for our React application.
featured image - How to use context API in React
Mandar Waghe HackerNoon profile picture

What is context API

Context API is a component structure that is provided by React to manage the states for all the levels of your application.

It will work the same way as redux and it helps you to replace redux or avoid using third party libraries for your application.

It will work the same as redux. We have to define our context and we just have to pass the values of context through the provider for our react application.

Let us see how to create context and how to use it in our react application by creating a simple counter application to react.

You must have installed node and npm. Then just create a new react project. Type the following command in your terminal.

npx create-react-app contex-api

Now you will have a react project, just create a folder with the name context inside /src folder and create an index.js file in it. This file will have a context for our counter application.

We will create a new context using the createContext() method of React. Copy the following code in your src/context/index.js file.

import React from “react”
export default React.createContext({
title: “Welcome to counter App!”,
counter: 0
});

In our context, we have defined two values one is a title and the other is counter to manage the count record for our counter application. Now we will see how to use those values inside our apps.

just replace the content of the App.js file with the following code.

import React from ‘react’;
import Context from “./context”
class App extends React.Component {
render(){
return (
<React.Fragment>
<Context.Consumer>
{context => (
<div style={{ display: ‘flex’, justifyContent: ‘center’, flexDirection: ‘column’, alignItems: ‘center’}}>
<h1>{context.title}</h1>
<div style={{ display: ‘flex’, flexDirection: ‘row’, justifyContent: ‘space-around’}}>
<button>Increment</button>
<p>Conter:- {context.counter}</p>
<button>Decrement</button>
</div>
</div>
)}
</Context.Consumer>
</React.Fragment>
);
}
}
export default App;

In the App.js file, we have imported the context which we had created earlier and we are using the values which are present inside that content using the Consumer method of React class. This is one of the ways to access the values which are present inside your context.

Now run the application. open your terminal and go to the respective folder and type the following line to your terminal.

npm start

Visit 

http://localhost:3000
.
you will see the following output.

We have accessed our context API inside render method using the Consumer method. Right now our increment and decrement buttons are not working. Let write code to get them into action.

We will write two functions increment() and decrement(), increment() function to increase the counter by one and decrement function to reduce counter by one.

Add the following code in our App.js file before the render method.

state = {
counter: 0
}
increment = () => {
this.setState({
counter: this.state.counter + 1
});
}
decrement = () => {
this.setState({
counter: this.state.counter — 1
});
}

So, we have our functions ready but if you went to

http://localhost:3000
then you will see our buttons are not working yet.

Because in our counter we are showing value which is present is context API and we are not updating context values yet. Let see how to update context values. For that, we will make some changes. We will create separate components for the title and counter. The title component will display the title of the application and the counter component will display the updated counter.

We will create a new folder component in /src folder and create two files in it. We will name it CounterTitle.js and Counter.js respectively.

Before that, we will do one thing we must have to update our context values as well, So let’s see how to update context values.

Now we will replace the App.js file with the following code.

import React from ‘react’;
import Context from “./context”
import Counter from “./component/Counter”
import CounterTitle from “./component/CounterTitle”
class App extends React.Component {
state = {
counter: 0
}
increment = () => {
this.setState({
counter: this.state.counter + 1
});
}
decrement = () => {
this.setState({
counter: this.state.counter — 1
});
}
render(){
return (
<React.Fragment>
<Context.Provider value={{ counter: this.state.counter }}>
<div style={{ display: ‘flex’, justifyContent: ‘center’, flexDirection: ‘column’, alignItems: ‘center’}}>
<CounterTitle />
<div style={{ display: ‘flex’, flexDirection: ‘row’, justifyContent: ‘space-around’}}>
<button onClick={this.increment}>Increment</button>
<Counter />
<button onClick={this.decrement}>Decrement</button>
</div>
</div>
)}
</Context.Provider>
</React.Fragment>
);
}
}
export default App;

In the above code, I have use Provider function in the place of the consumer. Consumer function is used if you want to access the value from our context and Provider function is used to update or change the values of context which will be available for all the components of the application.

We have imported Counter and CounterTitle components in App.js. Now let’s add the following code to the CounterTitle.js and Counter.js respectively.

add the following code to CounterTitle.js file.

import React, {useContext} from “react”
import Context from “../context”
export default function CounterTitle(){
const mycontext = useContext(Context);
return <h1>{mycontext.title}</h1>;
}

add the following code to Counter.js file.

import React, { useContext } from “react”
import Context from “../context”
export default function Counter(){
const mycontext = useContext(Context);
return <p>Counter: {mycontext.counter}</p>
}

If you look at both the files you will see we have used functional components and we didn’t use any consumer function. If we are using functional component and we have to use context API’s value then we have useContext() hook in react. We are able to use context API in class and functional components both. Now run the app again and you will see our app is working fine now. Hurray…

Conclusion

We have learned how to use context API in class and functional components.

If you want full code of the above counter app, you will get it on https://github.com/mvcman/Counter-App.git.