log/entry
Dark Mode & Theming Approach
Implementing Dark Mode without the Bloat
Dark mode is a standard requirement for modern web apps. Here is how I implemented it on this site without adding heavy dependencies.
The Strategy
- CSS Custom Properties (Variables): define colors for both
root(light) and[data-theme='dark']. - React Context: to manage the state and persist it to
localStorage. - System Preference: automatically detect if the user prefers dark mode.
CSS Setup
in index.css:
:root {
--bg-color: #ffffff;
--text-color: #1a1a1a;
/* ... other vars */
}
[data-theme='dark'] {
--bg-color: #0d1117;
--text-color: #e6edf3;
/* ... other vars */
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
The Context Provider
I created a ThemeContext that wraps the app. It checks localStorage on mount, or falls back to window.matchMedia('(prefers-color-scheme: dark)').
This ensures that when a user lands on the site, it immediately respects their preference.
Why This Matters
User experience is about respecting user choices. If someone has their OS set to dark mode, blinding them with a white screen is bad UX. By using CSS variables, the switch is semantic and performant, avoiding complex CSS-in-JS runtime overhead.