This code provides a context-based implementation for managing a theme...

August 28, 2025 at 12:40 PM

import { createContext, useContext, useEffect, useState } from "react"; type ThemeMode = "light" | "dark"; interface ThemeContextType { mode: ThemeMode; toggleMode: () => void; } const ThemeModeContext = createContext<ThemeContextType | undefined>(undefined); export const ThemeModeProvider = ({ children, }: { children: React.ReactNode; }) => { const [mode, setMode] = useState<ThemeMode>( (localStorage.getItem("themeMode") as ThemeMode) || "light" ); useEffect(() => { localStorage.setItem("themeMode", mode); }, [mode]); const toggleMode = () => { setMode((prev) => (prev === "light" ? "dark" : "light")); }; return ( <ThemeModeContext.Provider value={{ mode, toggleMode }}> {children} </ThemeModeContext.Provider> ); }; export const useThemeMode = (): ThemeContextType => { const context = useContext(ThemeModeContext); if (!context) throw new Error("useThemeMode must be used within ThemeModeProvider"); return context; };

This code provides a context-based implementation for managing a theme mode ("light" or "dark") in a React application. Here's a breakdown of what it does:

  1. Defines a ThemeMode type: A TypeScript type is defined for the mode with possible values of "light" or "dark".

  2. Defines a ThemeContextType interface: This interface specifies the structure of the context. It includes:

    • mode: The current theme mode ("light" or "dark").
    • toggleMode: A function to toggle the theme mode between "light" and "dark".
  3. Creates the ThemeModeContext:

    • A React Context is created using createContext. This context will hold the current theme mode and the toggle function.
    • Initially, the context is set to undefined to enforce that it is always used within a provider.
  4. Implements the ThemeModeProvider component:

    • This is a context provider that manages the theme mode state and provides it down the React component tree.
    • It reads the initial theme mode from localStorage, defaulting to "light" if none is set.
    • It listens for changes to the mode and stores the current mode in localStorage using useEffect.
    • It provides a toggleMode function, which switches the mode between "light" and "dark".
    • The provider wraps the children components and passes down the mode and toggleMode as context values.
  5. Creates the useThemeMode hook:

    • This is a custom React hook that makes it easy for components to consume the ThemeModeContext.
    • If used outside of the provider, an error is thrown to enforce proper usage.

Usage:

  • Wrap your application (or a portion of it) with the ThemeModeProvider to provide theme state and functionality.
  • Use the useThemeMode hook in child components to access the current mode and toggleMode function.

Example:

import React from "react";
import ReactDOM from "react-dom";
import { ThemeModeProvider, useThemeMode } from "./ThemeModeContext";

const App = () => {
  const { mode, toggleMode } = useThemeMode();

  return (
    <div style={{ backgroundColor: mode === "dark" ? "#333" : "#fff", color: mode === "dark" ? "#fff" : "#000" }}>
      <h1>Current Theme Mode: {mode}</h1>
      <button onClick={toggleMode}>Toggle Theme</button>
    </div>
  );
};

ReactDOM.render(
  <ThemeModeProvider>
    <App />
  </ThemeModeProvider>,
  document.getElementById("root")
);

Key Outcomes:

  • LocalStorage: Ensures the theme mode persists between page reloads.
  • Context: Provides a global state for managing the theme mode.
  • Custom Hook: Simplifies access to the theme functionality for components.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node