Global State in React
1. Introduction to Global State
Global state is application data that can be accessed by multiple components. Instead of maintaining separate copies of the same information in different components, we can share state through a common provider or a state management solution.
For example, a shopping cart may be displayed in the navbar, product page and checkout page. Global state allows these components to access the same cart information.
2. Why Do We Need Global State?
- Share common information across components.
- Avoid passing the same props through many intermediate components.
- Keep shared application data consistent.
- Manage shopping cart, theme and user preferences.
- Make shared state easier to maintain in larger applications.
3. Local State vs Global State
| Local State | Global State |
|---|---|
| Used within a particular component. | Shared across multiple components. |
Often managed using useState. |
Can use Context API or Redux Toolkit. |
| Example: form input value. | Example: shared shopping cart. |
| Usually simpler to manage. | Useful when shared state becomes more complex. |
4. Global State Using React Context
React Context allows us to share values with components without
passing props through every intermediate component. We create a
context, provide its value and read it using
useContext.
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
function toggleTheme() {
setTheme((currentTheme) =>
currentTheme === "light" ? "dark" : "light"
);
}
return (
<ThemeContext.Provider
value={{ theme, toggleTheme }}
>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (context === null) {
throw new Error(
"useTheme must be used within ThemeProvider"
);
}
return context;
}
5. Providing Global State to the Application
Wrap the application with ThemeProvider so its
child components can access the shared theme.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { ThemeProvider } from "./context/ThemeContext";
createRoot(document.getElementById("root")).render(
<StrictMode>
<ThemeProvider>
<App />
</ThemeProvider>
</StrictMode>
);
The provider is placed above the components that need access to the theme. Components outside this provider cannot use this context value.
6. Accessing Global State in a Component
The useTheme() custom Hook provides the current
theme and the function to toggle it.
import { useTheme } from "../context/ThemeContext";
function ThemeSwitcher() {
const { theme, toggleTheme } = useTheme();
return (
<div className={`theme-card ${theme}`}>
<h2>Current Theme: {theme}</h2>
<button onClick={toggleTheme}>
Toggle Theme
</button>
</div>
);
}
export default ThemeSwitcher;
7. Styling the Theme Component
.theme-card {
padding: 24px;
border-radius: 10px;
border: 1px solid #d1d5db;
transition: background-color 0.2s, color 0.2s;
}
.theme-card.light {
background-color: #ffffff;
color: #111827;
}
.theme-card.dark {
background-color: #1f2937;
color: #ffffff;
}
.theme-card button {
padding: 10px 16px;
border: none;
border-radius: 6px;
background-color: #2563eb;
color: #ffffff;
cursor: pointer;
}
8. Displaying the Component in App.jsx
import ThemeSwitcher from "./components/ThemeSwitcher";
import "./App.css";
function App() {
return (
<main>
<h1>Global State Example</h1>
<ThemeSwitcher />
</main>
);
}
export default App;
Expected Output
Current Theme: light
The component displays the current theme.
Clicking the button changes the theme state. The component re-renders to display the updated value.
9. Global State Flow
Multiple components can consume the same context value.
10. When Should You Use Global State?
- When multiple components need the same information.
- When application-wide preferences must remain consistent.
- When passing props through many intermediate components becomes difficult.
- When managing shared user interface state such as a theme or cart.
11. Practice Tasks
- Create a ThemeContext and a ThemeProvider.
- Display the theme in two different components.
- Add a button to switch between light and dark themes.
- Create a global language preference using Context.
- Build a shared cart count that can be displayed in the navbar and product page.
- Compare Context API with local component state.
Summary
Global state allows multiple React components to access shared application data. React Context can provide shared values without passing props through every intermediate component. By combining createContext, a provider, useContext and state Hooks, developers can manage shared information such as themes and user preferences.