Vinit Parekh
VINIT PAREKH's Blog

VINIT PAREKH's Blog

React Context API

Vinit Parekh's photo
Vinit Parekh
·Jun 18, 2022·

2 min read

Today we are going to talk about Context API in this blog.

so first of all you might have a question that

What is CONTEXT API?

so this is the simple definition:
"Context API is the way to pass the data through the multiple components without passing props."

Let's understand this with a simple example:

So in this example we are going to create a e-commerce product with contains some data for ex: price, variants, size, name, ratings

in React.org examples of the usage is provided in class components but here we are going to use functional components.

Step 1: create a folder named context where we will store the context files

//inside the productContext.jsx
import React, {createContext} from "react";

const productContext = createContext();

export default productContext;

Step 2: Now we are going to provide a data in this productContext for that create another file named productState.jsx

import ProductContext from "./productContext.jsx"

const ProductState = ({children}) => {
  const productData = {
    "name": "Classic T-shirt",
    "size": "XXL",
    "color": "red",
    "price": 499,
    "Ratings 4.5" 
  }

  return(
    <>
      <ProductContext.Provider value={productData}>
        {children}
      </ProductContext.Provider>
    </>

}

export default ProductState;

Explaination of above code:

First we included productcontext which we made in 1st step. then inside the ProductState we created a object which contains the details of the product and added it as Context value.

children props is passed so it act as product data.

We have successfully made a context api now lets use it in out App.js ( main file which comes with boilerplate

Step 3: In App.js we are going to use this context api

import {useContext} from "react";
import productContext from "../context/productContext";
import ProductState from "../context/productState"

const App = () => {
  const data = useContext(productContext)
  return(
    <div>
      <ProductState>
        <p> Product name: {data.name}</p>
        <p> Product price: {data.price}</p>
        <p> Product ratings: {data.ratings}</p>
       </ProductState>
    </div>
  )
}

export default App;

Thank you for reading my blog

 
Share this