JAVASCRIPT

Implement Global Theme Toggling with useContext

Easily manage global application themes, like dark and light modes, across your React components using the useContext hook for efficient state propagation without prop drilling.

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

const ThemeContext = createContext(null);

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

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

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <div style={{ background: theme === 'light' ? '#f0f0f0' : '#333', color: theme === 'light' ? '#333' : '#f0f0f0', minHeight: '100vh', padding: '20px' }}>
        {children}
      </div>
    </ThemeContext.Provider>
  );
};

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

// Example Component Usage
function ThemeSwitcher() {
  const { theme, toggleTheme } = useTheme();
  return (
    <div>
      <p>Current Theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

// How to use in App.js:
// function App() {
//   return (
//     <ThemeProvider>
//       <ThemeSwitcher />
//       {/* Other components that need theme */}
//     </ThemeProvider>
//   );
// }
// export default App;
How it works: The useContext hook provides a way to pass data through the component tree without having to pass props down manually at every level (prop drilling). By creating a Context and a Provider component, data (like the current theme and a toggler function) can be made available to any descendant component that consumes the context using the useContext hook. This pattern is excellent for managing global application settings or shared state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs