The Context API: A Deep Dive (Part 2) - A Practical Example of Creating and Consuming a Context #98
📖 Introduction
Following our introduction to the core concepts of the Context API, this article provides a practical, hands-on example of creating and consuming a context. We will build a simple theme switcher that allows a user to toggle between a light and dark mode.
📚 Prerequisites
Before we begin, please ensure you have a solid grasp of the following concepts:
- All concepts from Part 1 of this series.
- Basic CSS.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ Creating a Context Provider: How to create a component that provides a context value and a function to update it.
- ✅ Consuming Context in a Component: How to use the
useContext
hook to access the context value and the update function. - ✅ Practical Application: Building a theme switcher to toggle between light and dark mode.
🧠 Section 1: The Core Concepts of a Theme Switcher
A theme switcher is a classic example of a feature that benefits from the Context API. The theme is a global concern that can affect any component in the application. By using the Context API, we can provide the current theme and a function to update it to any component that needs it, without having to pass props down through the entire component tree.
💻 Section 2: Deep Dive - Implementation and Walkthrough
Let's build our theme switcher.
2.1 - The ThemeProvider
First, let's create a ThemeProvider
component that will manage the theme state and provide it to its children.
// ThemeProvider.js
import React, { useState, createContext } from 'react';
export const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
Step-by-Step Code Breakdown:
createContext()
: We create aThemeContext
.useState
: We useuseState
to manage thetheme
state.toggleTheme
: We create a function to toggle the theme.ThemeContext.Provider
: We provide thetheme
andtoggleTheme
function to the context.
2.2 - The ThemeSwitcher
Component
Now, let's create a ThemeSwitcher
component that will consume the context and allow the user to toggle the theme.
// ThemeSwitcher.js
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';
function ThemeSwitcher() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'Dark' : 'Light'} Mode
</button>
);
}
export default ThemeSwitcher;
Step-by-Step Code Breakdown:
useContext(ThemeContext)
: We use theuseContext
hook to get thetheme
andtoggleTheme
function from the context.onClick={toggleTheme}
: We call thetoggleTheme
function when the button is clicked.
2.3 - Integrating into App.js
Finally, let's wrap our application with the ThemeProvider
and use the ThemeSwitcher
component.
// App.js
import React from 'react';
import { ThemeProvider } from './ThemeProvider';
import ThemeSwitcher from './ThemeSwitcher';
import './App.css';
function App() {
return (
<ThemeProvider>
<div className="App">
<h1>Theme Switcher</h1>
<ThemeSwitcher />
</div>
</ThemeProvider>
);
}
export default App;
And here's some simple CSS to style our themes:
/* App.css */
.App {
padding: 2rem;
transition: background-color 0.3s, color 0.3s;
}
.App.light {
background-color: #fff;
color: #333;
}
.App.dark {
background-color: #333;
color: #fff;
}
To make this work, you'll need to add the theme to the className
of your main div
in App.js
:
// App.js (updated)
import React, { useContext } from 'react';
import { ThemeProvider, ThemeContext } from './ThemeProvider';
import ThemeSwitcher from './ThemeSwitcher';
import './App.css';
function AppContent() {
const { theme } = useContext(ThemeContext);
return (
<div className={`App ${theme}`}>
<h1>Theme Switcher</h1>
<ThemeSwitcher />
</div>
);
}
function App() {
return (
<ThemeProvider>
<AppContent />
</ThemeProvider>
);
}
export default App;
💡 Conclusion & Key Takeaways
In this article, we've built a practical example of a theme switcher using the Context API. We've seen how to create a provider component that manages state and provides it to its children, and how to consume that state in a nested component.
Let's summarize the key takeaways:
- The Context API is a powerful tool for managing global state in a React application.
- You can pass both values and functions through context, allowing nested components to update the context's value.
- A theme switcher is a classic example of a feature that benefits from the Context API.
Challenge Yourself:
To solidify your understanding, try to add a UserContext
to the application that provides a user's name and allows a nested component to update it.
➡️ Next Steps
You now have a solid understanding of how to create and consume a context. In the next article, "When to Use Context", we will discuss the ideal use cases for the Context API and when you might want to reach for a different state management solution.
Thank you for your dedication. Stay curious, and happy coding!
glossary
- Theme Switcher: A UI element that allows a user to switch between different visual themes (e.g., light and dark mode).
- Global State: State that is accessible to any component in the application.