How to Create a Dark Mode Toggle in React (Step-by-Step)

Dark mode has become a must-have feature in modern web applications. It enhances accessibility, reduces eye strain, and improves overall user experience. In this step-by-step guide, youโ€™ll learn how to implement a clean and reusable dark mode toggle in React using best practices.

๐Ÿญ. ๐—ฆ๐—ฒ๐˜ ๐—จ๐—ฝ ๐—ฎ ๐—ก๐—ฒ๐˜„ ๐—ฅ๐—ฒ๐—ฎ๐—ฐ๐˜ ๐—ฃ๐—ฟ๐—ผ๐—ท๐—ฒ๐—ฐ๐˜

If you donโ€™t already have a project:

npx create-react-app dark-mode-toggle
cd dark-mode-toggle

This gives you a fresh React environment to work with.

๐Ÿฎ. ๐—–๐—ฟ๐—ฒ๐—ฎ๐˜๐—ฒ ๐—ฎ ๐—ง๐—ต๐—ฒ๐—บ๐—ฒ ๐—ฆ๐˜๐—ฎ๐˜๐—ฒ ๐—จ๐˜€๐—ถ๐—ป๐—ด ๐˜‚๐˜€๐—ฒ๐—ฆ๐˜๐—ฎ๐˜๐—ฒ

Inside your main component (e.g., App.js), create a theme state to store light or dark mode:

const [theme, setTheme] = useState(\"light\");

const toggleTheme = () => {
  setTheme((prev) => (prev === \"light\" ? \"dark\" : \"light\"));
};

This simple toggle function flips between themes on button click.

๐Ÿฏ. ๐—”๐—ฝ๐—ฝ๐—น๐˜† ๐—ง๐—ต๐—ฒ๐—บ๐—ฒ ๐—–๐—น๐—ฎ๐˜€๐˜€ ๐˜๐—ผ ๐˜๐—ต๐—ฒ ๐—ฅ๐—ผ๐—ผ๐˜ ๐—˜๐—น๐—ฒ๐—บ๐—ฒ๐—ป๐˜

We want the entire UI to change colors, so apply the theme class to a wrapper:

<div className={`app ${theme}`}>
  <button onClick={toggleTheme}>Toggle Dark Mode</button>
</div>

Now your styles will adapt based on the active theme class.

๐Ÿฐ. ๐—”๐—ฑ๐—ฑ ๐—Ÿ๐—ถ๐—ด๐—ต๐˜ & ๐——๐—ฎ๐—ฟ๐—ธ ๐— ๐—ผ๐—ฑ๐—ฒ ๐—ฆ๐˜๐˜†๐—น๐—ฒ๐˜€

In App.css:

.app.light {
  background: #ffffff;
  color: #000000;
}

.app.dark {
  background: #121212;
  color: #ffffff;
}

button {
  padding: 12px 18px;
  cursor: pointer;
}

This ensures clean visual transitions.

๐Ÿฑ. (๐—ข๐—ฝ๐˜๐—ถ๐—ผ๐—ป๐—ฎ๐—น) ๐—ฆ๐—ฎ๐˜ƒ๐—ฒ ๐—ง๐—ต๐—ฒ๐—บ๐—ฒ ๐—ฃ๐—ฟ๐—ฒ๐—ณ๐—ฒ๐—ฟ๐—ฒ๐—ป๐—ฐ๐—ฒ ๐—ถ๐—ป ๐—Ÿ๐—ผ๐—ฐ๐—ฎ๐—น ๐—ฆ๐˜๐—ผ๐—ฟ๐—ฎ๐—ด๐—ฒ

To remember user preference:

useEffect(() => {
  localStorage.setItem(\"theme\", theme);
}, [theme]);

useEffect(() => {
  const saved = localStorage.getItem(\"theme\");
  if (saved) setTheme(saved);
}, []);

๐—™๐—ถ๐—ป๐—ฎ๐—น ๐—ง๐—ต๐—ผ๐˜‚๐—ด๐—ต๐˜๐˜€

Creating a dark mode toggle in React is simple yet powerful. With just a few lines of code, you can improve user comfort and give your application a modern, polished feel. You can extend this setup with animations, theme context providers, or CSS variables for more advanced theming.

If you are looking for any services related to Website Development, App Development, Digital Marketing and SEO, just email us at nchouksey@manifestinfotech.com

#DarkModeReact #ReactDarkMode #ReactTutorial #ReactJS #ReactDevelopment #FrontendDevelopment #WebDevelopment #DarkModeToggle #JavaScriptTutorial #ModernWebDev #ReactGuide #UIDesign #UXDesign #CodingTips #ReactDevCommunity #LearnReact #ReactBeginners #ReactSteps #TechGuide #ProgrammingTips