← Back to all snippets
JAVASCRIPT

Global Theme Toggle with useContext

Learn to implement a global theme toggle in React applications using useContext for efficient state sharing without prop drilling, improving UI consistency.

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

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

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

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

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

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

// Example Usage (in App.js or a component)
/*
function App() {
  return (
    <ThemeProvider>
      <ThemedComponent />
    </ThemeProvider>
  );
}

function ThemedComponent() {
  const { theme, toggleTheme } = useTheme();

  return (
    <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#333' : '#fff', minHeight: '100vh', padding: '20px' }}>
      <h1>Current Theme: {theme}</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
      <p>This text changes based on the theme.</p>
    </div>
  );
}
*/
How it works: This snippet demonstrates how to create a global theme context using `createContext` and `useContext`. The `ThemeProvider` component wraps your application, making the `theme` state and `toggleTheme` function available to any descendant component. The `useTheme` custom hook provides a convenient and type-safe way for components to access and interact with the theme context, avoiding prop drilling for global state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs