React Context
Key concepts to remember
- Context: React's Context allows for efficient sharing of state across components. It provides a mechanism to pass data through the component tree without explicit prop drilling.
- Global State Management: With Context, we can manage the global state effectively. It eliminates the tedious process of passing props through multiple intermediate components, making accessing shared data from any component within the context easier.
- Simplifying Patterns: Context simplifies the implementation of specific patterns in React, such as theme switching or authentication. For example, by using Context, we can easily change the theme of the entire application by updating a single context value, which automatically propagates the changes to all components consuming that context.
Example
Let's create a simple app that displays different sections of text. The primary objective is to dynamically change the app's styles based on the selected theme. We will offer two options: light and dark. Using React Context will ensure that all components know the chosen theme and adapt the colors accordingly.
Step 1
We create the context in the separate context.js file.
import { createContext } from "react";
const ThemeContext = createContext();
export default ThemeContext;
Code explanation:
- Line 1: This line imports the
createContextfunction from the "react" package. ThecreateContextfunction is used to create a new context object in React. - Line 3: This line creates a new context object called
ThemeContextusing thecreateContextfunction. - Line 5: This line exports the
ThemeContextobject as the default export of the module. By doing so, other modules can import and use this context in their components.
Step 2
We build the entire app within the App.jsx file and implement the logic to toggle the colors upon button click. Additionally, we wrap the entire app with the context to ensure that all components have access to the shared data, which, in this case, is the theme.
import React, { useEffect, useState } from "react";
import ThemeContext from "../context";
import Header from "../Header/Header";
import Body from "../Body/Body";
import Footer from "../Footer/Footer";
import "../index.css";
const App = () => {
const [theme, setTheme] = useState("light");
useEffect(() => {
document.body.style.backgroundColor =
theme === "light" ? "#FFFFF0" : "#413839";
}, [theme]);
const handleButtonClick = () => {
setTheme(theme === "light" ? "dark" : "light");
};
return (
<ThemeContext.Provider value={theme}>
<button onClick={handleButtonClick}>Toggle Theme</button>
<Header />
<Body />
<Footer />
</ThemeContext.Provider>
);
};
export default App;
Code explanation:
- Line 1-6: The code imports the necessary dependencies, including the
useEffectanduseStatehooks, along with the required components and CSS file. - Line 9-14: The
Appcomponent initializes thethemestate variable and sets up an effect that updates the body background color based on thethemevalue. - Line 16-18: The
handleButtonClickfunction toggles the theme between "light" and "dark" when the button is clicked. - Line 20-27: The JSX return statement renders the components, wrapping them in the
ThemeContext.Providerto provide thethemevalue to the child components. - Line 30: The
Appcomponent is exported as thedefault export, allowing it to be imported and used in other application parts.
Step 3
Next, we proceed to the child components. We will focus on one component in detail since the logic remains the same for all of them. Let's take the Header component as an example. By utilizing the context, we can access the theme value and dynamically adjust the color based on the current theme value.
import React, { useContext } from "react";
import ThemeContext from "../context";
import s from "./Header.module.css";
const Header = () => {
const theme = useContext(ThemeContext);
return (
<header className={theme === "light" ? s.light : s.dark}>
<div>
<h1 className={s.heading}>Fuel Your Creativity</h1>
<p>
Some text...
</p>
</div>
</header>
);
};
export default Header;
Code explanation:
- Line 1-3: The code imports necessary dependencies, including
ReactanduseContext. - Line 5-6: The
Headercomponent is defined, which uses theuseContexthook to access thethemevalue from theThemeContext. - Line 8-17: The JSX markup represents the
Headercomponent, where theclassNameof theheaderelement is conditionally set based on thethemevalue. - Line 20: The
Headercomponent is exported as thedefault export, allowing it to be imported and used in other application parts.
Complete code
To change the theme, please click the Toggle Theme button in the top right corner of the Code Sandbox.
1. What is the purpose of the Context in React?
2. Which hook is used to access the context values in a functional component?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 1.96
React Context
Swipe to show menu
Key concepts to remember
- Context: React's Context allows for efficient sharing of state across components. It provides a mechanism to pass data through the component tree without explicit prop drilling.
- Global State Management: With Context, we can manage the global state effectively. It eliminates the tedious process of passing props through multiple intermediate components, making accessing shared data from any component within the context easier.
- Simplifying Patterns: Context simplifies the implementation of specific patterns in React, such as theme switching or authentication. For example, by using Context, we can easily change the theme of the entire application by updating a single context value, which automatically propagates the changes to all components consuming that context.
Example
Let's create a simple app that displays different sections of text. The primary objective is to dynamically change the app's styles based on the selected theme. We will offer two options: light and dark. Using React Context will ensure that all components know the chosen theme and adapt the colors accordingly.
Step 1
We create the context in the separate context.js file.
import { createContext } from "react";
const ThemeContext = createContext();
export default ThemeContext;
Code explanation:
- Line 1: This line imports the
createContextfunction from the "react" package. ThecreateContextfunction is used to create a new context object in React. - Line 3: This line creates a new context object called
ThemeContextusing thecreateContextfunction. - Line 5: This line exports the
ThemeContextobject as the default export of the module. By doing so, other modules can import and use this context in their components.
Step 2
We build the entire app within the App.jsx file and implement the logic to toggle the colors upon button click. Additionally, we wrap the entire app with the context to ensure that all components have access to the shared data, which, in this case, is the theme.
import React, { useEffect, useState } from "react";
import ThemeContext from "../context";
import Header from "../Header/Header";
import Body from "../Body/Body";
import Footer from "../Footer/Footer";
import "../index.css";
const App = () => {
const [theme, setTheme] = useState("light");
useEffect(() => {
document.body.style.backgroundColor =
theme === "light" ? "#FFFFF0" : "#413839";
}, [theme]);
const handleButtonClick = () => {
setTheme(theme === "light" ? "dark" : "light");
};
return (
<ThemeContext.Provider value={theme}>
<button onClick={handleButtonClick}>Toggle Theme</button>
<Header />
<Body />
<Footer />
</ThemeContext.Provider>
);
};
export default App;
Code explanation:
- Line 1-6: The code imports the necessary dependencies, including the
useEffectanduseStatehooks, along with the required components and CSS file. - Line 9-14: The
Appcomponent initializes thethemestate variable and sets up an effect that updates the body background color based on thethemevalue. - Line 16-18: The
handleButtonClickfunction toggles the theme between "light" and "dark" when the button is clicked. - Line 20-27: The JSX return statement renders the components, wrapping them in the
ThemeContext.Providerto provide thethemevalue to the child components. - Line 30: The
Appcomponent is exported as thedefault export, allowing it to be imported and used in other application parts.
Step 3
Next, we proceed to the child components. We will focus on one component in detail since the logic remains the same for all of them. Let's take the Header component as an example. By utilizing the context, we can access the theme value and dynamically adjust the color based on the current theme value.
import React, { useContext } from "react";
import ThemeContext from "../context";
import s from "./Header.module.css";
const Header = () => {
const theme = useContext(ThemeContext);
return (
<header className={theme === "light" ? s.light : s.dark}>
<div>
<h1 className={s.heading}>Fuel Your Creativity</h1>
<p>
Some text...
</p>
</div>
</header>
);
};
export default Header;
Code explanation:
- Line 1-3: The code imports necessary dependencies, including
ReactanduseContext. - Line 5-6: The
Headercomponent is defined, which uses theuseContexthook to access thethemevalue from theThemeContext. - Line 8-17: The JSX markup represents the
Headercomponent, where theclassNameof theheaderelement is conditionally set based on thethemevalue. - Line 20: The
Headercomponent is exported as thedefault export, allowing it to be imported and used in other application parts.
Complete code
To change the theme, please click the Toggle Theme button in the top right corner of the Code Sandbox.
1. What is the purpose of the Context in React?
2. Which hook is used to access the context values in a functional component?
Thanks for your feedback!