← Back to all snippets
JAVASCRIPT

React useContext for Global Theme Management

Implement a global theme in your React app using the useContext hook and Context API to easily pass theme values down the component tree without prop drilling.

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

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

// 2. Create a Provider Component
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>
  );
}

// 3. Create a Consumer Component (optional, can use useContext directly)
function ThemedComponent() {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff', padding: '20px' }}>
      <h1>Current Theme: {theme}</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

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

export default App;
How it works: The `useContext` hook, combined with the React Context API, provides a way to pass data deeply through the component tree without manually passing props at every level (prop drilling). First, `createContext` defines a new context. Then, a `Provider` component wraps the part of the component tree that needs access to the context's value, passing it via its `value` prop. Finally, any descendant component can consume this value using `useContext(ThemeContext)`, making global state management like theme toggling straightforward and efficient.

Need help integrating this into your project?

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

Hire DigitalCodeLabs