← Back to all snippets
JAVASCRIPT

Efficient Global State with `useContext` for Theme Toggling

Learn how to implement global state management in React using `useContext` to easily toggle application themes without prop drilling. Simplify component communication.

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

const ThemeContext = createContext(null);

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>
  );
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === null) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}

// Example Usage in a component:
// function App() {
//   return (
//     <ThemeProvider>
//       <Toolbar />
//     </ThemeProvider>
//   );
// }

// function Toolbar() {
//   const { theme, toggleTheme } = useTheme();
//   return (
//     <div style={{ background: theme === 'dark' ? '#333' : '#eee', color: theme === 'dark' ? '#eee' : '#333', padding: '20px' }}>
//       Current Theme: {theme}
//       <button onClick={toggleTheme} style={{ marginLeft: '10px' }}>Toggle Theme</button>
//     </div>
//   );
// }
How it works: This snippet demonstrates `useContext` for creating a global theme provider. `ThemeContext.Provider` makes `theme` and `toggleTheme` available to any child component. The `useTheme` custom hook simplifies consuming this context, allowing components to access and modify the theme without prop drilling, making state management cleaner and more efficient across the application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs