DEV Community

Cover image for Learning to toggle Dark Mode through React Hooks
Ellaine Tolentino
Ellaine Tolentino

Posted on

Learning to toggle Dark Mode through React Hooks

I recently revisited a project of mine and found a feature that I think I can recreate with the use of React Hooks.

My current goal is to try out things from React to deepen my familiarity of it and maybe others can relate or give tips to #codenewbies like myself about React Hooks. So if you have any resource suggestions, feel free to drop them in the comments below!

So for starters..

The app that I mentioned is called SplashGlam. It is powered by ReactJS and hosted through Heroku. Feel free to toggle the day and night mode using the button on the top navigator to see what are we working with.

On Day/Bright mode..
Day mode

On Night/Dark mode..
Night mode

I also have discussed how I built the toggling feature using LocalStorage on my other blog.(What is LocalStorage?) This time around, I wanted to try Hooks to recreate at least the toggling part.

I created a repo to test things out and feel free to check it out if you wanted to test it out on your own. Github repo

Small breakdown of my code:


JSX for DOM elements-So I built the elements on the page first with the corresponding attributes needed like an onClick eventListener.


Function snapshot-Here's how I incorporate useState in the toggle & using a function that has an if statement to trigger changes.


CSS! Now that we have our functions and elements all set. Remember our function has a line of code where we change/replace the className of the body from dayMode to nightMode?

Here's my corresponding CSS to see DOM change!
CSS snapshot


Day Mode

Night Mode

And that is pretty much it! I hope anyone that needs an example in using hooks to toggle day/night mode find this helpful!

Let me know if I missed anything in the comments please! Until the next!

Top comments (2)

lelepg profile image
Letícia Pegoraro Garcez

That's a very elegant solution, but I wonder if using CSS variables to store colors and just change these variables according to the light or dark pallet would be a viable solution as well...

tolentinoel profile image
Ellaine Tolentino

That might actually work too! I haven’t tried it myself but I think I’ve seen a youtube video inline with using CSS variables!