Sequence NODE_187
MediumImplement Dark/Light Theme Toggle
React
JavaScript
Technical Specification
Create a toggle that switches between dark and light theme and applies a class to the body.
Input/Output Samples
Input:Toggle theme
Output:Body class toggles between light and dark
Optimal Logic Path
import { useState, useEffect } from "react";
function ThemeToggle() {
const [theme, setTheme] = useState("light");
useEffect(() => {
document.body.dataset.theme = theme;
}, [theme]);
return (
<button
onClick={() =>
setTheme((t) => (t === "light" ? "dark" : "light"))
}
>
Current: {theme}
</button>
);
}Architectural Deep-Dive
We keep the theme in state and update a body attribute whenever it changes.