Context API in React

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

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store