With context you can pass data through the components without passing props manually at the entry level.
React has a data flow and it’s a top-down or parent-child approach but you might not want to follow it every single time especially while developing UI themes or similar apps. Because those kind of apps have many components and it becomes hard to follow that top-down data flow.
That’s when context comes into rescue. You can use context to share data between components bypassing that top-down data flow explicitly.
Example Without Context
This is how we do it without using context:
In the example below, the toolbar component takes a theme prop and pass it to the ThemeButton.
class App extends React.Component {
render() {
return ;
}
}
function Toolbar(props) {
return (
);
}
class ThemedButton extends React.Component {
render() {
return ;
}
}
Imagine how much complicated task it will become to pass theme to every single button we add.
Contexts are like global variables defined by the user and can be used anywhere in the app.
Example With Context
Let’s use content now so that we can finally avoid passing the props in those intermediate elements.
Step 1: Create Context
Let’s create a context for the current theme and “light” as the default value.
const ThemeContext = React.createContext('light');
Step 2: Use a Provider
Now, we need to use a Provider to pass the current theme. Any component can read the theme and modify the default value. Let’s add a “dark” value to it.
class App extends React.Component {
render() {
return (
);
}
}
Step 3: Assign a contextType
Now, we need to read the current theme context and to do so we need to assign a contextType. Once we do that, React will find a closest Provider above and then grab it’s value to use it.
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return ;
}
}
Bringing all together
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
);
}
}
function Toolbar() {
return (
);
}
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return ;
}
}
Credit: React Docs
components context contextType Global props provider