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.