Context API in React

Rajan Lagah
2 min readFeb 15, 2021

--

Sharing states and functions between components ? This can be done using React Context api

I believe you already have existing react app and you want to use Context api. So i am taking example in which we will pass theme for app to route’s components

in src create new file ContextProviders/theme.js

import React,{createContext,useState} from 'react'  export const ThemeDataContext = createContext() const ThemeContext = ( props ) => { 
const [theme,setTheme] = useState('dark')
return(
<ThemeDataContext.Provider value={{
theme,
setTheme}}>
{props.children}
</ThemeDataContext.Provider>
)}
export default ThemeContext

Now this we can share to components we want

I have added react-router-dom to manage routes so in App.js

import React from 'react';
import { BrowserRouter as Router, Switch, Route,} from "react-router-dom";
function App() {
return (
<Router>
<Switch>
<ThemeContext>
<Route exact path="/landingPage" component={LandingPage} />
<Route exact path="/products" component={ProductDisplay} />
</ThemeContext>
</Switch>
</Router>
);
}
export default App;

Now components in these routes can use the values that we have pass in out theme context.

in LangingPage.js we can

import {ThemeDataContext} from '../../ContextProviders/theme';const LandingPage = () => {    
const { theme } = useContext(ThemeDataContext)
....

Hopefully this help you in adding context api in your react app.

From experience 👷

Don’t replace redux(if using) in your existing app with context api. I did same and my components are updating in stupid manner i.e. if child component need to get update it will trigger update for parent component too when i was using Context in both components. I then read doc here and found

All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant consumers (including .contextType and useContext) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update.

So be careful. Also using context api for theme is perfect 😆

--

--

Rajan Lagah
Rajan Lagah

Written by Rajan Lagah

React expert and Deep learning beginner.

No responses yet