DEV Community

Cover image for How to Use the React Context API in Your Projects
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

How to Use the React Context API in Your Projects

Managing the state is an essential part of developing applications in React. A common way to manage the state is by passing props. Passing props means sending data from one component to another. It's a good way to ensure data gets to the right place in a React application.

1. Create a New React App

npx create-react-app contextapi

Enter fullscreen mode Exit fullscreen mode

2. Create the Context

Create an App.js file in your project and createContext in this App.js as well we have put some data like name, price, info and image in the component.

  • Setting up state using useState.
  • Providing context to child components.

App.js

import React, { useState } from "react";
import Home from "./Home";

import { createContext } from "react";

export const UserContext = createContext();
function App() {
  const [stuName, setStuName] = useState({
    name: "Bowie Alderney Sofa",
    price: "INR : 25,000/-",
    info: "One of the many things that make a house a home is a 
     beautiful, comfortable sofa or armchair.",
    image:
      "./image.jpg",
  });

  return (
    <>
      <UserContext.Provider value={{ stuName, setStuName }}>
        <Home />
      </UserContext.Provider>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

3. Create the Home.jsx Component.
if you want to access data then we need to use useContext, First we have import usecontextand use it.

  • Displaying product details.
  • Using context to access state.

Home.jsx

import React from "react";

import { useContext } from "react";
import { UserContext } from "./App";

import Products from "./Products";
import Cart from "./Cart";

function Home() {
  const users = useContext(UserContext);
  return (
    <div>
      <div className="container">
        <div>
          <div class="card mt-5" style={{ width: "18rem" }}>
            <img
              class="card-img-top"
              src={users.stuName.image}
              alt="Card image cap"
            />
            <div class="card-body">
              <h4 class="card-title">{users.stuName.name}</h4>
              <h3 class="card-title">{users.stuName.price}</h3>
              <p class="card-text">{users.stuName.info}</p>
              <a href="#" class="btn btn-primary">
                <Cart />
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Home;

Enter fullscreen mode Exit fullscreen mode

4.Creating the Cart Component

  • Using useContext to consume context.
  • Updating state with a button click.
import React from "react";
import { useContext } from "react";
import { UserContext } from "./App";
function Cart() {
  const users = useContext(UserContext);
  return (
    <>
      <button
        class="btn btn-primary"
        onClick={() => {
          users.setStuName({
            name: "Sofas",
            price: "INR : 55,000/-",
            info: "One of the many things that make a house a home is a 
            beautiful, comfortable sofa or armchair.",
            image:
              "./image02.jpg",
          });
        }}
      >
        Update Cart
      </button>
    </>
  );
}

export default Cart;

Enter fullscreen mode Exit fullscreen mode

5. Run the Application
Finally, start the React development server.

npm start

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Top comments (0)