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
