JAVASCRIPT

Implement Global Theming with useContext

Discover how to manage global application themes efficiently using React's `useContext` hook, allowing components to consume theme data without prop drilling and manage state.

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

  const value = { theme, toggleTheme };

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

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

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

  const style = {
    backgroundColor: theme === 'light' ? '#fff' : '#333',
    color: theme === 'light' ? '#333' : '#fff',
    padding: '20px',
    margin: '10px',
    border: '1px solid #ccc'
  };

  return (
    <div style={style}>
      <p>Current Theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

// App entry point to wrap with Provider
function App() {
  return (
    <ThemeProvider>
      <ThemedComponent />
      {/* Other components that need the theme can be here */}
    </ThemeProvider>
  );
}

export default App;
How it works: This example sets up a global theme using `useContext`. `ThemeContext` is created, and `ThemeProvider` wraps part of the component tree, providing the current `theme` state and a `toggleTheme` function. The `useTheme` custom hook simplifies consuming this context, allowing any descendant component to access and modify the theme without the need for prop drilling, fostering a cleaner and more maintainable codebase.

Need help integrating this into your project?

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

Hire DigitalCodeLabs