How to implement dark mode in a React app?

To implement dark mode in a React app, you can follow these steps:

  1. Create a context for managing the theme state:
import React, { createContext, useState, useContext } from 'react'; const ThemeContext = createContext(); export const ThemeProvider = ({ children }) => { const [isDarkMode, setIsDarkMode] = useState(false); const toggleDarkMode = () => { setIsDarkMode(prevMode => !prevMode); }; return ( <ThemeContext.Provider value={{ isDarkMode, toggleDarkMode }}> {children} </ThemeContext.Provider> ); }; export const useTheme = () => useContext(ThemeContext);
  1. Wrap your app with the ThemeProvider component in your main App.js file:
import React from 'react'; import { ThemeProvider } from './ThemeContext'; import Home from './Home'; const App = () => { return ( <ThemeProvider> <Home /> </ThemeProvider> ); }; export default App;
  1. Use the useTheme hook in your components to access the theme state and toggle function:
import React from 'react'; import { useTheme } from './ThemeContext'; const Home = () => { const { isDarkMode, toggleDarkMode } = useTheme(); return ( <div className={isDarkMode ? 'dark-mode' : ''}> <h1>Welcome to my dark mode app!</h1> <button onClick={toggleDarkMode}>Toggle Dark Mode</button> </div> ); }; export default Home;
  1. Add CSS styles for dark mode in your index.css or a separate CSS file:
body.dark-mode { background-color: #333; color: #fff; }
  1. Start your app and test the dark mode functionality by clicking on the "Toggle Dark Mode" button.

Now, you have successfully implemented dark mode in your React app using a context provider and hook.