DEV Community

Fatima Alam
Fatima Alam

Posted on

Context API Syntax

Functional Components

Component where the context is defined and which provides the actual component with the context.

const functionalComponent = () => {

...
return(
<>
<contextName.Provider value = "contextValue">
<ComponentThatUsesTheContext />
</contextName.Provider>
</>
)
}
Enter fullscreen mode Exit fullscreen mode

Component where the context is to be used (uses useContext hook)

const ComponentThatUsesTheContext = () => {
const {contextUser} =  useContext(contextName);
...
return(
<>
{contextUser}
</>
)
}
Enter fullscreen mode Exit fullscreen mode

Class Components

Creating context


const contextName = React.createContext();
const contextProvider = contextName.Provider;
const contextConsumer = contextName.Consumer;
export {contextProvider , contextConsumer }
Enter fullscreen mode Exit fullscreen mode

Component where the context is defined and which provides the actual component with the context.

import contextProvider;

class classComponent extends React.Component{
render(){
return(
<>
<contextProvider value = "contextValue">
<ComponentThatUsesTheContext />
</contextProvider>
</>
)
}
}
Enter fullscreen mode Exit fullscreen mode

consumer ->

import contextProvider;

class ComponentThatUsesTheContext extends React.Component{
render(){
return(
<>
<contextConsumer>
{(contextTaken) => {
return(
<>
contextTaken
</>
)
}
}
</contextConsumer>
</>
)
}
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)