DEV Community

Cover image for Context API in React
Madhuban Khatri
Madhuban Khatri

Posted on

Context API in React

What is Context API in React

Context API is a concept of sending data from one parent component to its children components. It is used to reduce Prop Drilling in the react app. Now your question is what is prop drilling?

Prop Drilling

Suppose a person wants to go from the topmost ladder to the lowest ladder, he will go down the stairs one by one.

Similarly in react, if the lowest component wants to use a prop that is defined in its topmost parent component then that prop is shared among the components between them and these intermediate components send the prop to the lowest component without processing this prop.

Prop Drilling

Why Context API

Prop drilling can make the code more difficult to read and maintain, and can also make it harder to refactor the components later on. So context API can be used to send data without using prop drilling.

How to use Context API

First of all we need to keep some keywords in our mind in context API -

  • createContext- it is used to create a context object
  • Provider- it is used to wrap the components that will use the props.
  • useContext - it is used to fetch data from context object

Create a Context.js file

import { createContext } from "react"
const MyContext = createContext("");
export default MyContext
Enter fullscreen mode Exit fullscreen mode

Create a MyComponent.js file

import { useContext } from "react";
import MyContext from "./Context";

function MyComponent(){
    const {count, setCount} = useContext(MyContext);

            <h1>MY Component</h1>
            <button onClick={()=>setCount(count+1)}>Click</button>

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

App.js file

In this file, we will use Context API's Provider to wrap the MyComponent and some values are sending as value prop to wrapped component.

import { useState } from "react";
import MyComponent from "./MyComponent";
import MyContext from "./Context";

function App() {
  const [count, setCount] = useState(0)

  return (
        <MyContext.Provider value={{count, setCount}}>
export default App
Enter fullscreen mode Exit fullscreen mode

Top comments (0)