How to Implement Dark Mode in Your React App

Reading Time: 5 min read

Introduction

Dark mode has become a popular feature in modern web applications, offering users a visually appealing and comfortable experience, especially in low-light environments. In this post, we'll explore how to implement dark mode in your React application using CSS variables and the Context API.

Setting Up the Project

First, create a new React project if you don't already have one:

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

Creating a Theme Context

We'll use the Context API to manage the theme state and provide a way to toggle between light and dark modes.

Create ThemeContext.js

import React, { createContext, useState, useContext } from 'react'
 
const ThemeContext = createContext()
 
export const useTheme = () => useContext(ThemeContext)
 
export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light')
 
  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'))
  }
 
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  )
}

Applying Themes with CSS Variables

Next, we'll define CSS variables for light and dark themes and apply them based on the current theme.

Create styles.css

:root {
  --bg-color: #ffffff;
  --text-color: #000000;
}
 
[data-theme='dark'] {
  --bg-color: #121212;
  --text-color: #ffffff;
}
 
body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition:
    background-color 0.3s,
    color 0.3s;
}

Using the Theme in Your App

Now, we'll integrate the ThemeContext into our application and add a button to toggle between themes.

Update index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './styles.css'
import App from './App'
import { ThemeProvider } from './ThemeContext'
 
ReactDOM.render(
  <ThemeProvider>
    <App />
  </ThemeProvider>,
  document.getElementById('root'),
)

Update App.js

import React, { useEffect } from 'react'
import { useTheme } from './ThemeContext'
 
const App = () => {
  const { theme, toggleTheme } = useTheme()
 
  useEffect(() => {
    document.body.setAttribute('data-theme', theme)
  }, [theme])
 
  return (
    <div>
      <h1>Dark Mode Example</h1>
      <button onClick={toggleTheme}>
        Switch to {theme === 'light' ? 'Dark' : 'Light'} Mode
      </button>
    </div>
  )
}
 
export default App

Conclusion

Adding dark mode to your React application enhances the user experience and provides a modern touch to your interface. By using CSS variables and the Context API, you can efficiently manage and switch between themes. Try implementing dark mode in your project and see the difference it makes.

For more detailed guidance, refer to the React documentation.

Go back Home.