JAVASCRIPT

Global Theme Management in React with `useContext`

Efficiently manage global UI states like themes in your React app using `useContext`. Implement a simple theme switcher, avoiding prop drilling for clean code.

import React, { createContext, useContext, useState } from 'react';

// 1. Create a Context
const ThemeContext = createContext(null);

// 2. Create a Provider Component
export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light'); // 'light' or 'dark'

  const toggleTheme = () => {
    setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  const value = { theme, toggleTheme };

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

// 3. Create a Custom Hook to Consume the Context
export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}

// Example Usage:
function ThemedComponent() {
  const { theme, toggleTheme } = useTheme();

  const containerStyle = {
    padding: '20px',
    backgroundColor: theme === 'light' ? '#f0f0f0' : '#333',
    color: theme === 'light' ? '#333' : '#f0f0f0',
    borderRadius: '8px',
    textAlign: 'center',
    margin: '20px auto',
    maxWidth: '400px'
  };

  const buttonStyle = {
    padding: '10px 15px',
    fontSize: '16px',
    cursor: 'pointer',
    marginTop: '15px',
    backgroundColor: theme === 'light' ? '#ddd' : '#555',
    color: theme === 'light' ? '#333' : '#f0f0f0',
    border: 'none',
    borderRadius: '5px'
  };

  return (
    <div style={containerStyle}>
      <h1>Current Theme: {theme.toUpperCase()}</h1>
      <button style={buttonStyle} onClick={toggleTheme}>
        Toggle Theme
      </button>
      <p>This component's theme is managed globally.</p>
    </div>
  );
}

// App structure would be:
// function App() {
//   return (
//     <ThemeProvider>
//       <ThemedComponent />
//     </ThemeProvider>
//   );
// }
// export default App;
How it works: This pattern demonstrates setting up global state management using `useContext`. `ThemeContext` is created, and `ThemeProvider` wraps components that need access to the theme. The `useTheme` custom hook provides a convenient way for child components to consume the current `theme` and the `toggleTheme` function without prop drilling, making global state accessible.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs