1. Global State with React Context API
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
⊞Code Example
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("dark");
const toggleTheme = () => setTheme(t => t === "dark" ? "light" : "dark");
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// Deep child component consuming global context
export function ThemeToggleButton() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button onClick={toggleTheme} className="theme-pill">
Current Theme: {theme} (Click to toggle)
</button>
);
}
