React Context API: Advantages & Disadvantages

What is Context API?

Advantages & Disadvantages

Steps to Use Context API in Functional Components

import {createContext} from 'react';const YourContext = createContext('this is the initial value');export default ThemeContext;
import YourContext from "../contexts/YourContext.";
import ChildComponent from "../components/ChildComponent";
function App(){
return(
<YourContext.Provider value={'Hello world'}>
<ChildComponent/>
</YourContext.Provider>
)}
export default App;
import {useContext} from "react";
import YourContext from "../contexts/YourContext"
function ChildComponent(){
const MyContext = useContext(YourContext);
}
export default ChildComponent;

Using Context API with Class Based Components

import YourContext from "../contexts/YourContext"
import React, { Component } from 'react'
export default class ChildComponent extends Component {static contextType = YourContext;render() {
return (
<div>
{this.context}
</div>
)}}
import YourContext from "../contexts/YourContext"
import React, { Component } from 'react'
export default class ChildComponent extends Component {render() {
return (
<div>
<YourContext.Consumer>
{(value)=> updateValue(value)}
</YourContext.Consumer>
</div>
)}}

Conclusion

Resources

--

--

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