⚡ Building Dark Mode in React – The Smart & Scalable Way

Noura MostafaNoura Mostafa
2 min read

Dark Mode isn’t just a trend — it’s now a user expectation. Whether you're building a portfolio or a SaaS dashboard, supporting dark mode can seriously improve user experience. Let’s explore the smartest way to implement dark mode in React using useEffect, localStorage, and Tailwind CSS.


🎯 Why Add Dark Mode?

  • 🌙 Saves battery on OLED screens

  • 🧘 Reduces eye strain at night

  • 💼 Gives a polished, professional feel to your UI


🧱 Setup: Tailwind + React Project

Make sure Tailwind is configured for dark mode:

jsCopyEdit// tailwind.config.js
module.exports = {
  darkMode: 'class', // Enables class-based dark mode
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: { extend: {} },
  plugins: [],
}

🧠 Step 1: Create a Custom Hook useDarkMode

jsCopyEditimport { useEffect, useState } from "react";

export default function useDarkMode() {
  const [theme, setTheme] = useState(() => {
    return localStorage.getItem("theme") || "light";
  });

  useEffect(() => {
    document.documentElement.classList.toggle("dark", theme === "dark");
    localStorage.setItem("theme", theme);
  }, [theme]);

  return [theme, setTheme];
}

🌗 Step 2: Toggle Button Component

jsCopyEditimport useDarkMode from "./useDarkMode";

export default function ThemeToggle() {
  const [theme, setTheme] = useDarkMode();

  return (
    <button
      onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
      className="p-2 bg-gray-200 dark:bg-gray-800 rounded"
    >
      {theme === "dark" ? "☀️ Light" : "🌙 Dark"}
    </button>
  );
}

🎨 Step 3: Add Dark Styles

htmlCopyEdit<div className="bg-white text-black dark:bg-gray-900 dark:text-white">
  <h1 className="text-2xl font-bold">Welcome to My App</h1>
</div>

🚀 Final Thoughts

✅ Persistent with localStorage
✅ Works with Tailwind and custom styles
✅ Clean and scalable for real-world projects

Adding dark mode isn’t hard — but doing it right makes your app stand out!

0
Subscribe to my newsletter

Read articles from Noura Mostafa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Noura Mostafa
Noura Mostafa

🚀 Aspiring Full-Stack Developer Blogger 👨‍💻 Passionate about web development and coding. ✍️ Sharing my journey through tech via CodeOdyssey 🌍 "The code is a journey, not a destination."