Implementing Dark Mode in React: A Simple Approach
Dark mode has become a preferred interface option for many users, offering a visually soothing experience especially in low-light environments. If you are a React developer looking to implement dark mode in your applications, you’ve come to the right place. In this article, we will explore the concepts and methods for implementing dark mode effectively in a React application.
Understanding Dark Mode
Dark mode is a display setting that uses a dark color palette for app interfaces, providing a low-haemoglobin view that reduces eye strain compared to bright, white backgrounds. It not only enhances user experience but can also save battery life on OLED displays.
Why Use Dark Mode?
- Reduced Eye Strain: Users can benefit from a more comfortable reading experience, especially in low-light environments.
- Battery Preservation: Particularly for OLED screens, dark mode can save power.
- User Preference: Many users have a personal preference for dark mode due to aesthetic reasons or visibility comfort.
Setting Up a Basic React Application
Before we dive into implementing dark mode, let’s set up a simple React application. Run the following command in your terminal to create a new React app:
npx create-react-app dark-mode-example
Navigate into your newly created app:
cd dark-mode-example
Now, you can start the development server with:
npm start
Implementing Dark Mode: Step-by-Step
Step 1: Defining Theme Styles
To implement dark mode, we first need to define styles for both light and dark modes. Create a new file named themes.js in the src folder of your application:
const lightTheme = {
backgroundColor: '#ffffff',
color: '#000000'
};
const darkTheme = {
backgroundColor: '#000000',
color: '#ffffff'
};
export { lightTheme, darkTheme };
Step 2: Creating a Theme Context
Now, let’s create a context to manage the theme throughout your application. Create a new file called ThemeContext.js in the src folder:
import React, { createContext, useState, useEffect } from 'react';
import { lightTheme, darkTheme } from './themes';
export const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState(lightTheme);
const [isDarkMode, setIsDarkMode] = useState(false);
useEffect(() => {
setTheme(isDarkMode ? darkTheme : lightTheme);
}, [isDarkMode]);
const toggleTheme = () => {
setIsDarkMode(!isDarkMode);
};
return (
{children}
);
};
export default ThemeProvider;
Step 3: Wrapping Your Application with ThemeProvider
To make the theme available throughout your application, you need to wrap your application with the ThemeProvider. Open index.js and do the following:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import ThemeProvider from './ThemeContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
Step 4: Using the Theme in Your Components
Next, you can use the theme context in your components. Open App.js and update it as follows:
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
const App = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
Hello, World!
);
};
export default App;
How It Works
When you click the toggle button, the toggleTheme function reverses the isDarkMode state. This triggers a re-evaluation of the theme in the useEffect hook, automatically updating the styles throughout the app.
Styling Your Components
For a better user experience, let’s add some custom styles. You may want to create a CSS module or just add inline styles. Here’s an example of how to create a CSS module:
.App {
transition: background-color 0.5s ease, color 0.5s ease;
}
Then, import and apply it in your App.js:
import './App.css'; // Importing the CSS
const App = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
Hello, World!
);
};
Persisting the Theme Preference
To enhance user experience, consider saving the user’s theme preference in local storage. You can do this by modifying your ThemeProvider.js:
useEffect(() => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
setIsDarkMode(savedTheme === 'dark' ? true : false);
}
}, []);
const toggleTheme = () => {
setIsDarkMode(!isDarkMode);
localStorage.setItem('theme', !isDarkMode ? 'dark' : 'light');
};
Final Touch: Adding Transitions
To make the transition smoother, you can style the elements with a CSS transition. Here’s how:
body {
transition: background-color 0.3s linear, color 0.3s linear;
}
Testing Your Implementation
Run your application and test the dark mode toggle. You should see a seamless transition between light and dark themes. If you refresh your page, your preference will still be intact thanks to local storage.
It’s also advisable to test your application to ensure that it meets accessibility standards. Make sure color contrasts are sufficient for users with visual impairments.
Conclusion
Implementing dark mode in your React applications brings both functionality and improved aesthetics, enhancing user engagement and satisfaction. By leveraging React’s context API, you can efficiently manage themes across your app while maintaining code simplicity.
Now that you have a functional dark mode implementation in your React application, feel free to extend features like automatic detection based on the user’s system preferences or integrating with styling libraries such as styled-components or css-modules.
Happy coding!
2 Comments
Good post. I learn something totally new and challenging on blogs I stumbleupon every day.
It’s always interesting to read through content from other authors and use something from their sites.
It’s hard to find educated people in this particular subject, but
you sound like you know what you’re talking about! Thanks