Functional Components
Component where the context is defined and which provides the actual component with the context.
…
return(
<>
<contextName.Provider value = “contextValue“>
<ComponentThatUsesTheContext />
</contextName.Provider>
</>
)
}
Component where the context is to be used (uses useContext hook)
const {contextUser} = useContext(contextName);
…
return(
<>
{contextUser}
</>
)
}
Class Components
Creating context
const contextName = React.createContext();
const contextProvider = contextName.Provider;
const contextConsumer = contextName.Consumer;
export {contextProvider , contextConsumer }
Component where the context is defined and which provides the actual component with the context.
class classComponent extends React.Component{
render(){
return(
<>
<contextProvider value = “contextValue“>
<ComponentThatUsesTheContext />
</contextProvider>
</>
)
}
}
consumer ->
class ComponentThatUsesTheContext extends React.Component{
render(){
return(
<>
<contextConsumer>
{(contextTaken) => {
return(
<>
contextTaken
</>
)
}
}
</contextConsumer>
</>
)
}
}