Skip to content

react context is giving undefined object

In my react application I am trying to use context api. In my component I am importing the context but it is giving error that object can not destructure the property. I am trying to implement cart functionality in my app. I am using hooks.


import React, { createContext, useState } from 'react';

const ImgContext = createContext();

const ImgConProvider = ({children}) => {
    const [myCart, setMyCart] = useState([]);

    <ImgContext.Provider value={{myCart, setMyCart}}>

export {ImgContext, ImgConProvider}


import React, { useContext, useState } from 'react';
import ImageGrid from './ImageGrid';
import { ImgContext } from './Context/ImageContext';

const Home = () => {

    const { myCart } = useContext(ImgContext);

    return (
    <div className="App">

export default  Home;



You are not providing a a default value when creating the context. If there is a scenario where the component doenst have access to a provider the value from context would be undefined which maybe causing the issue. Better provide a default value.

const ImgContext = createContext({});