Adding a dark mode to your web app is no longer just a "nice-to-have"—it’s expected. It’s about accessibility, user comfort, and yes, giving your product that sleek, modern feel that users love.
In this guide, I’ll walk you through building a simple dark mode toggle in React. No unnecessary fluff—just a clean, effective implementation you can build in minutes.
🎯 Why Dark Mode Matters
Dark mode isn’t a gimmick—it’s UX with empathy. It reduces eye strain, improves readability in low-light environments, and gives users a choice in how they experience your app.
Modern design is about personalization. And this one toggle says, “I care about the user.”
🧠 Step 1: Manage Theme State with useState
To begin, we’ll set up a basic state to toggle between light and dark themes using React hooks.
import React, { useState } from 'react';
function App() {
const [darkMode, setDarkMode] = useState(false);
return (
<div className={darkMode ? 'dark' : 'light'}>
<button onClick={() => setDarkMode(!darkMode)}>
Toggle Dark Mode
button>
<h1>Hello, World!h1>
div>
);
}
export default App;
With just a few lines of code, we’ve added dynamic theme switching to our app.
🎨 Step 2: Define the Styles
Style each theme clearly so the UI updates visually when toggled.
/* index.css */
.light {
background-color: #ffffff;
color: #000000;
}
.dark {
background-color: #121212;
color: #ffffff;
}
button {
margin-top: 20px;
padding: 10px 20px;
cursor: pointer;
border: none;
background-color: #444;
color: #fff;
border-radius: 5px;
}
This is a minimal and clean look—but you can build on it with transitions, animations, or even full theme objects.
🛠️ Step 3: Enhance the Experience
A basic toggle is great—but here’s how to make it even better:
-
Persist user preference with
localStorage
. -
Respect system theme using
window.matchMedia()
. - Add smooth transitions for a polished feel.
These touches take the experience from functional to exceptional.
Made with ❤️ for modern front-end developers.
I hope this was helpful, and I’d be happy to connect and follow each other!