Create dark mode in React js using redux hooks

Manish Mandal
How To React
Published in
3 min readJan 24, 2022

After a long time, I am writing something on the medium. So I thought let's share one of the most required feature in React that’s Dark mode. Dark mode lets your website visitors view your content in their preferred mode like dark or light. This is one of the features which mode of the developer ignores while developing the site. So let me help you with the dark mode integration on your React js project.

Note: In this tutorial, I am going to use redux hooks so I am not going to discuss much in detail how to set up redux in react js, you can follow my previous tutorial How to use Redux with React Hooks and Axios for that Or you can use my react-redux boilerplate from here.

  1. First, we will create a toggle button to toggle dark and light mode. So open your app.js file and paste the below code. (This will require you to install react icons npm install react-iconsto use icons. I have used icons to make the toggle more attractive but this is optional you can remove the icon code from the HTML).

2. Now open your app.css file and paste the below CSS code.

Now your toggle button will look something like this

3. Now it’s time to work with redux. So first go to your types.js file and declare a DARK_MODE variable

4. Ok so now it’s time to create a state for the dark mode to be accessed anywhere anytime on any component. So, Open your reducers directory inside the store directory and create a file called darkModeReducer.js, and inside that file paste the below code. Everything has been explained inside the code.

5. Now call this darkModeReducer.js file inside your reducer main file that’s index.js file inside the reducer folder.

6. Now prepare your darkModeAction.js file inside your action folder and paste the below code inside that file.

7. Ok so as we have prepared our store with reducer and action it’s time to use that state inside our main app.js file where we have created our toggle button. Open your app.js file and paste the below code.

You can use the isDarkMode state anywhere in any component you just need to call your darMode state from the reducer using the useSelector hook of redux like we have used from lines no. 12 to 15 in the app.js file.

For demonstration purposes, I have shown only the way to change the body color but you can change any color of any HTML element if you use inline styling or a third-party styling library like styled-components.

For any query, you can get in touch with me via LinkedIn

That’s it for today I’ll come with another tutorial on another day. I have also shared the Github repository and live code for you to test. Thanks for reading.

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/