Context provides a way to pass data from the root component to any child components without having to pass it manually as a relay from component to component.
Thus solving the prop drilling issue, also context comes in handy while passing a store across the application.
For example, If you are using a third-party store management library like MobX in your application then you could use context and make the store available across the application.
The context consists of the Provider and Consumer components, You use Provider component to pass the prop and Consumer component to receive props.
To implement context in your application you need to perform below three steps i.e Creating Context, Pass or Provide Context, and lastly Consume Context.
Step 1: Create Context (ThemeContext.js)
import React from 'react';
export const ThemeContext = React.createContext();
Step 2: Passing Global State From Your Main Component (App.js)
The way you do that is by wrapping the main component with the provider component and passing the props into it, as shown in the below example.
import React from 'react';
import './style.css';
import Parent from './Parent';
import { ThemeContext } from './ThemeContext';
export default function App() {
const [theme, setTheme] = React.useState('Dark');
const globalState = {
theme: theme,
setTheme: setTheme
};
return (
<ThemeContext.Provider value={globalState}>
<div className={theme}>
<Parent />
</div>
</ThemeContext.Provider>
);
}
Step 3: Consuming Global State In Any Child Component
We use Consumer component to receive props, but unlike provider, consumer component expects the child component to be a function component so that it could pass context state as a prop to child components. Example below.
import React from 'react';
import { ThemeContext } from './ThemeContext';
const Child = () => {
return (
<ThemeContext.Consumer>
{({ theme, setTheme }) => {
return (
<button
onClick={() => {
setTheme(theme === 'Dark' ? 'Light' : 'Dark');
}}
>
{theme + ' Theme'}
</button>
);
}}
</ThemeContext.Consumer>
);
};
export default Child;
Done, you have successfully passed the global state deep into the application without having to pass it manually from component to component.
You could refer to this example onstackblitz,
Happy Coding !!