Introduction
Dark mode has become a standard feature in modern web applications. Users prefer it for better readability, reduced eye strain, and improved battery performance on devices.
If you are building a modern UI, implementing a dark mode toggle in React is almost expected. The good news is that it is not complex if approached step by step with a clean structure.
In this guide, we will learn how to implement a dark mode toggle in React using state management, CSS variables, and persistent storage. This approach is widely used in React applications, UI/UX design systems, and modern frontend development.
What is Dark Mode in React?
Dark mode is a UI feature that switches the application theme from light colors to darker colors.
Instead of redesigning everything, we dynamically change styles based on a theme state.
Why Dark Mode is Important
Improves user experience
Reduces eye strain in low light
Saves battery on OLED screens
Enhances modern UI design
How Dark Mode Works Internally
At a high level, dark mode works by:
Storing the current theme (light or dark)
Applying styles based on that theme
Updating UI when the theme changes
In React, this is typically handled using state and CSS.
Step 1: Create a React Project
npx create-react-app dark-mode-app
cd dark-mode-app
npm start
Explanation
Creates a new React application
Starts development server
Provides base setup for UI implementation
Step 2: Create Theme State
Inside your main component (App.js):
import { useState } from "react";
function App() {
const [theme, setTheme] = useState("light");
return (
<div>
<h1>Dark Mode Example</h1>
</div>
);
}
export default App;
Explanation
themestores current mode (light or dark)setThemeupdates the modeDefault theme is light
Step 3: Create Toggle Function
const toggleTheme = () => {
setTheme(theme === "light" ? "dark" : "light");
};
Explanation
Checks current theme
Switches between light and dark
Triggers UI re-render automatically
Step 4: Apply Theme Class to Root
return (
<div className={theme}>
<button onClick={toggleTheme}>Toggle Theme</button>
<h1>Dark Mode Example</h1>
</div>
);
Explanation
Adds class based on current theme
CSS will control appearance
Button triggers theme change
Step 5: Define CSS for Themes
Create styles in App.css:
.light {
background-color: white;
color: black;
}
.dark {
background-color: #121212;
color: white;
}

Join the conversation! Your thoughts help the community grow.