javascriptreactjsreact-contextcreatecontext

createContext undefined


When I try to use createContext() the console gives me this error:

App.js:6
Uncaught TypeError: Cannot destructure property 'consoleLogFunction' of '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is null.

I've seen others asking questions about this here in Stack Overflow but I can't find a solution.

GlobalContext.js

import React from 'react'
import { createContext } from 'react'

export const AppContext = createContext();

function GlobalContext() {
    const consoleLogFunction = () => {
        console.log("ok")
    }
    return (
        <AppContext.Provider value={{consoleLogFunction}}></AppContext.Provider>
    )
}

export default GlobalContext

App.js

import "./index.css";
import { useContext, useEffect } from "react";
import { AppContext } from "./components/GlobalContext";

function App() {
  const { consoleLogFunction } = useContext(AppContext);
  useEffect(() => {
    consoleLogFunction();
  }, []);

  return (
    <AppContext>
      <div>home</div>
    </AppContext>
  );
}

export default App;


Solution

  • You don't need to export 'AppContext', creating the provider and exporting that is good enough.

    Try this, I've also made a couple of modifications to make it easier to use the context later:

    GlobalContext.js

    import React from 'react'
    import { createContext, useContext } from 'react'
    
    const AppContext = createContext();
    
    function GlobalContext({ children }) {
        const consoleLogFunction = () => {
            console.log("ok")
        }
        return (
          <AppContext.Provider value={{consoleLogFunction}}>
            { children }
          </AppContext.Provider>
        )
    }
    
    export default GlobalContext;
    
    // This is a helper
    export const useGlobalContext = () => useContext(AppContext);
    

    Home.js

    import { useEffect } from "react";
    import { useGlobalContext } from "./components/GlobalContext";
    
    export const Home = ({ children }) => {
      const { consoleLogFunction } = useGlobalContext();
    
      useEffect(() => {
        consoleLogFunction();
      }, []);  
    
      return(
        <div>home</div>
      )
    };
    
    

    App.js

    import "./index.css";
    import { useEffect } from "react";
    import GlobalContext from "./components/GlobalContext"
    import { Home } from "./components/Home";
    
    function App() {
      return(
        <GlobalContext>
          <Home />
        </GlobalContext>
      );
    }
    
    export default App;