Skip to solution
easyMachine Coding

Build a Dark Mode Toggle

1.1k views
01

Understand the problem

Build a theme toggle that persists the user's choice.

ReactThemeState
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Solve in

A dark mode toggle is a controlled boolean that (1) flips a theme, (2) persists the choice, and (3) applies it to the page.

The mental model

Hold one dark boolean. Derive colors from it and persist it to localStorage so a refresh remembers.

const [dark, setDark] = useState(() => {
  try { 

Solution ready — 2 min read

Classified // press E to declassify

04

React solution

Complete solutionRun Playground
import { useState, useEffect } from 'react';
import DarkModeToggle from './src/DarkModeToggle';

export default function App() {
  const [dark, setDark] = useState(() => {
    try { return localStorage.getItem('theme') === 'dark'; } catch { return false; }
  });

  useEffect(() => {
    try { localStorage.setItem('theme', dark ? 'dark' : 'light'); } catch {}
  }, [dark]);

  return (
    <div style={{
      minHeight: '100vh', fontFamily: 'system-ui, sans-serif', padding: 40, textAlign: 'center',
      background: dark ? '#0f172a' : '#ffffff', color: dark ? '#e2e8f0' : '#111111',
      transition: 'background 0.3s, color 0.3s',
    }}>
      <h2>Dark Mode Toggle</h2>
      <p style={{ opacity: 0.7 }}>Your preference is saved to localStorage.</p>
      <DarkModeToggle value={dark} onChange={setDark} />
      <p style={{ marginTop: 20 }}>Theme: <strong>{dark ? 'dark' : 'light'}</strong></p>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 3 of 87 decoded in the Frontend Machine Coding track. One more won't hurt.

Back to track