useContext is not working in my react code

Viewed 2340

App Component:

    import React,{createContext} from "react";
    import "./style.css";
    import A from "./A";
    
    export const userContext =createContext();
    
    function App() {
      return (
        <userContext.Provider name={"samuel"}>
          <div>
            <A />
          </div>
        </userContext.Provider>
      );
    }
    export default App;

Component A

    import React from 'react';
    import B from './B';
    function A(){
      return (<div>
      <h3>Component A </h3>
      <B />
      </div>)
    }
    
    export default A;

Component B:

        import React, { useContext } from "react";
        import {userContext} from "./App";
    
    function B() {
      const name = useContext(userContext);
      return (
        <div>
          <h3>Component B{name} </h3>
        </div>
      );
    }
    
    export default B;

The context value that I passed at App component is not getting consumed at Component B.

Context is used to pass data directly to an component instead of being passing to each component that comes in the path of the destination component. So that the component that does not require the data do not get access to it. I am using useContext hook instead of Context.consumer api at the receiver component.

1 Answers

You have to pass a value to the Provider in this case you want to pass a string, whereas you were previously passing an object with the wrong keyword name.

Another issue I found was that you were using B to extract the value from context but you were not placing it under the scope of which components have access to the context:

function App() {
  return (
    <userContext.Provider value="samuel">
      <div>
        <A />
        <B />
      </div>
    </userContext.Provider>
  );
}
export default App;

This works now and you can check the codesandbox.

Related