Master state management in modern React applications by sharing state globally across components without prop drilling.
1. The Prop Drilling Problem
2. Creating Context with createContext
Create a Context object and establish fallback default values:
⊞Code Example
import { createContext } from 'react';
// Create context with sensible default values
export const ThemeContext = createContext({
theme: 'dark',
toggleTheme: () => {}
});
3. The Context Provider Pattern
Wrap your component tree in a custom Provider component that owns and manages the state:
⊞Code Example
import React, { useState } from 'react';
import { ThemeContext } from './ThemeContext';
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('dark');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'dark' ? 'light' : 'dark'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<div className={theme === 'dark' ? 'bg-[#060c18] text-white' : 'bg-white text-slate-900'}>
{children}
</div>
</ThemeContext.Provider>
);
}
4. Consuming State with useContext
Create a custom consumer hook to safely access the context anywhere in your application:
⊞Code Example
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
5. Complete Global State Implementation
Here is how consumer components cleanly toggle and read global state:
⊞Code Example
import React from 'react';
import { useTheme } from './ThemeContext';
export function HeaderNav() {
const { theme, toggleTheme } = useTheme();
return (
<header className="flex items-center justify-between p-4 border-b border-slate-800">
<h1 className="text-xl font-bold">Nextsem Academy</h1>
<button
onClick={toggleTheme}
className="px-4 py-2 bg-[#04AA6D] hover:bg-[#039861] text-white font-bold rounded-lg transition-colors"
>
Current Theme: {theme.toUpperCase()}
</button>
</header>
);
}
