In this article, we will see how to use React Context API using the useContext hook. Below is an example code that will help you to understand, how to create React context and how to use it.


react context api


What is a context API?

Context API is an easy way to create global variables that can be passed around in the react app and this is an alternative to props drilling.

So now let's see how do we use the context API and how do we use the use context hook to consume the context. So for that what  I am going to do is I am going to create a very simple component that is a counter component with two buttons, one would increase the count, and then the other would decrease the count.

React Context API  using useContext hook example?

Step: 1

Let me create a new file called CounterContext.js and add the below code to it.

We have to import createContext from React in order to create a context in react application, then we have to return Context Provider along with values. Below is the code for your reference

import { useState, createContext } from 'react'

export const CounterContext = createContext()

function CounterContextProvider(props) {

const [count, setcount] = useState(0)


function increaseCount() {
setcount(count + 1)
}

function decreaseCount() {
setcount(count - 1)
}
const value = { count, increaseCount, decreaseCount }
return (
<CounterContext.Provider value={value}>
{props.children}
</CounterContext.Provider>
)
}

export default CounterContextProvider


Step: 2

So let me create a new file inside the components folder which is called MyCounter.js

import React, { useContext } from 'react'
import { CounterContext } from '../components/contexts/CounterContext'

function MyCounter() {
const { count, increaseCount, decreaseCount } = useContext(CounterContext)


return (
<div>
<h1>Counter component</h1>
<p>Count is: {count}</p>
<button onClick={increaseCount} >Increase count</button>
<button onClick={decreaseCount}>Decrease count</button>

</div>
)
}

export default MyCounter

Step: 3

Let me create a new file called ComponentA.js and add the below code to it

import React, { useContext } from 'react'

import { CounterContext } from '../components/contexts/CounterContext'

function ComponentA() {
const { count } = useContext(CounterContext)
return (
<div>
<p>Count: {count}</p>
</div>
)
}

export default ComponentA

Step: 4

Let's import all the components in the App.js file
import ComponentA from './components/ComponentA'
import CounterContextProvider from './components/contexts/CounterContext'
import MyCounter from './components/MyCounter'

function App() {
return (
<CounterContextProvider>
<h1>Context API</h1>
<MyCounter />
<ComponentA />
</CounterContextProvider>
);
}

export default App;

Thanks for reading this article, I will see you in the next one.

If you want to know more about React routes, please go through the below links