reactjsreact-hooksreact-contextuse-contextcreatecontext

React.useContext appearing as undefined


This is my first time using the React context hooks in an app and my context default value keeps appearing as "undefined."

Troubleshooting so far:

All of my code can be found in this CodeSandbox link below:

https://codesandbox.io/s/react-context-troubleshooting-ojnb2?file=/src/child.js


Solution

  • In your App.js file, you're passing value a string:

    import React, { useContext } from "react";
    import { SelectedBackgroundContext } from "./context";
    import Child from "./child";
    
    function App() {
      const { selectedBackground } = useContext(SelectedBackgroundContext);
    
      // selectedBackground is just a string, so value = "https://...", which is invalid, the value, in your case, should be an object
      return (
        <SelectedBackgroundContext.Provider value={selectedBackground}>
          <Child />
        </SelectedBackgroundContext.Provider>
      );
    }
    
    export default App;
    

    Instead, value needs to be an object, with a selectedBackground property that contains the string:

    import React, { useContext } from "react";
    import { SelectedBackgroundContext } from "./context";
    import Child from "./child";
    
    function App() {
      const { selectedBackground, selectBackground } = useContext(
        SelectedBackgroundContext
      );
      // alternatively, just collect all context, without destructuring,
      // and pass it to the "value" prop: value={context}
      // const context = useContext(SelectedBackgroundContext);
    
    
      // you're also missing the "selectBackground" function, which should be added to this "value" prop
      return (
        <SelectedBackgroundContext.Provider
          value={{ selectedBackground, selectBackground }}
        >
          <Child />
        </SelectedBackgroundContext.Provider>
      );
    }
    
    export default App;
    

    Since you've created context using an object:

    {
      selectedBackground:
        "https://lp-cms-production.imgix.net/2019-06/81377873%20.jpg?fit=crop&q=40&sharp=10&vib=20&auto=format&ixlib=react-8.6.4",
      selectBackground: () => {}
    }
    

    The value property of the provider should also be an object!

    value={{ selectedBackground, selectBackground }}
    

    Working demo:

    Edit React Context Troubleshooting (forked)