5

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.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
Samuel T
  • 233
  • 2
  • 12

1 Answers1

1

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.

yudhiesh
  • 6,383
  • 3
  • 16
  • 49
  • Ya it works.I have an doubt even if i pass object it works only when i specify the keyword value Is it mandatory to mention value keyword in the Provider? Cant we use out own naming Like in my code i had mentioned Is it mandatory to give – Samuel T Mar 20 '21 at 04:35
  • @SamuelT also [this video](https://www.youtube.com/watch?v=lhMKvyLRWo0) does a great job of explaining how to use the `useContext` hook with a more complex example – yudhiesh Mar 20 '21 at 04:37
  • @SamuelT you have to use the keyword `value`. – yudhiesh Mar 20 '21 at 04:38