skip to Main Content

I want to use UseContext hook in my react app that’s some simple shop app,that has landing page and a shop.I want to share cart info in all of my components,I’ve been followign the guide how to do this but it doesn’t work (I get the default value which is null)

CartProvider.jsx

import { createContext, useContext, useState } from "react";

const CartContext = createContext(null);

const CartProvider = ({ children }) => {
  const [cart, setCart] = useState([]);

  const addToCart = (item) => {
    setCart([...cart, item]);
  };

  return (
    <CartContext.Provider value={{ cart, addToCart }}>
      {children}
    </CartContext.Provider>
  );
};
const useCart = () => {
  const context = useContext(CartContext);
  if (!context) {
    throw new Error("useCart must be used within a CartProvider");
  }
  return context;
};
export { CartProvider, useCart };

My app structure:

function App() {
  return (
    <>
      <CartProvider>
        <NavBar />
        <main>
          <div className="main-header">
            <h1 className="main-header">
              Browse our richest and fanciest collections on Shooppy!
            </h1>
          </div>
          <div className="button-section">
            <h2> Explore our offers now!</h2>

            <Link to="/shop">Online shop</Link>
          </div>
        </main>
      </CartProvider>
    </>
  );
}

I want to acces it in navbar for example:

export function NavBar() {
  const { cart } = useCart();

  return (
//...
   (

and I get the default value null which causes the error.
Also will,this works even when I’m using React Router?

2

Answers


  1. If you are not providing any value in the like this <CartProvider value={defaultValue}, then it will take the value which was initially set i.e. const CartContext = createContext(null). Also it works even if you’re using React Router. Hope this answers your query.

    Login or Signup to reply.
  2. To access the context in NavBar component, you should deconstruct the context.
    First you should export the context itself from the CartProvider.jsx:

    export const CartContext = createContext(null)
    

    or

    export { CartProvider, useCart, CartContext }
    

    then use it in the NavBar:

    import { useContext } from 'react'
    import { CartContext } from 'CartProvider'
    
    export function NavBar() {
      const { cart } = useContext(CartContext)
    
      return (
          //...
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search