Build a theme toggle that persists the user's choice.
01
01
Understand the problem
ReactThemeState
02
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Stuck? AI Nudge Available
Get a conceptual hint to guide your logic without spoiling the final implementation.
03
03
Study the solution
Solve in
The solution is waiting
Give it an honest attempt first — then compare your thinking with the full walkthrough.
04
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
05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.