The Context API in React provides a way to share values like themes, user data, or other global state between components without having to explicitly pass props through every level of the component tree. It's designed to solve the "prop drilling" problem, where data needs to be passed through many nested components.
This example demonstrates a theme context that lets components access and update the current theme without prop drilling. Click the button to toggle between light and dark themes.
Current theme: light
// ThemeContext.tsx
import React, { createContext, useState, ReactNode } from "react";
// Define the shape of the context
type ThemeContextType = {
theme: string;
toggleTheme: () => void;
};
// Create the context with default values
export const ThemeContext = createContext<ThemeContextType>({
theme: "light",
toggleTheme: () => {},
});
// Create a provider component
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === "light" ? "dark" : "light"));
};
// The context value that will be passed to consuming components
const contextValue = {
theme,
toggleTheme,
};
return (
<ThemeContext.Provider value={contextValue}>
{children}
</ThemeContext.Provider>
);
};
// Usage in components:
// const { theme, toggleTheme } = useContext(ThemeContext);