Context API

Amol Gunjal
2 min readJul 3, 2021

The Context API can be used to share data with multiple components, without having to pass data through props manually. For example, in some use cases, the Context API is ideal for theming, user language, authentication, etc.

createContext

To start with the Context API, the first thing we need to do is create a context using the createContext function from React.

const ThemeContext = createContext('Dark');

The createContext function accepts an initial value, but this initial value is not required.

Provider

The Provider component is going to be used to wrap the components that are going to have access to our context.

<ThemeContext.Provider value={this.state.theme}>
...
</ThemeContext.Provider>

The Provider component receives a prop called value, which can be accessed from all the components that are wrapped inside Provider, and it will be responsible to grant access to the context data.

Consumer

After you wrap all the components that are going to need access to the context with the Provider component, you need to tell which component is going to consume that data.

The Consumer component allows a React component to subscribe to the context changes. The component makes the data available using a render prop.

<ThemeContext.Consumer>
{(theme)=> <h1>Theme, {theme}</h1>}
</ThemeContext.Consumer>

useContext hook

The useContext hook allows us to connect and consume a context. The useContext hook receives a single argument, which is the context that you want to have access to.

const theme = useContext( ThemeContext );

The useContext is way better and cleaner than the Consumer component—we can easily understand what’s going on and increase the maintainability of our application.

For more reference see react guide for context

--

--