Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Image by Alex Andrews from Pexels

React Dark Mode hook

Feb 1, 2021

DESCRIPTION

We'll create useDarkMode hook to switch between light and dark themes. Our application will be built on top of styled-components and the Material UI Switch component.

Preview

Switch themes

React - useDarkMode.js
  • To avoid magic strings we create a THEME mapper to keep our string values.
  • Then we add defaultTheme and darkModeTheme objects with CSS properties.
  • Additionally, there is a THEME_MAPPER to map string value to a theme object.
  • useDarkMode hook uses useState to keep track of the currently selected theme string value.
  • toggleTheme switches currently selected theme string value.
  • Lastly, we return the theme object based on the string value (using THEME_MAPPER), toggleTheme function, and isDarkMode boolean which we'll use in our App.js.
React - App.js
  • We're using styled-components, Material UI Switch Component, and a little bit of JSX to create our example application.
  • GlobalStyles component is used to apply CSS to html tag based on the selected theme.
  • Inside of the App component we use our useDarkMode hook to get all 3 previously mentioned properties.
  • Then, we supply the currently selected theme to the ThemeProvider, thanks to that, the theme can be used in the GlobalStyles component.
  • Toggle is created using Switch component and we assign checked={isDarkMode} and onChange={toggleTheme} to it.
  • Lastly, we finish the rest of our application with simple HTML tags.

Summary

  • We created a simple theme switcher application using less than 100 lines of code.
  • Feel free to extend the number of themes and create some theme selector to practice a little bit more.
  • Combining various tools can speed up the development process like crazy. (use with caution 😅)
  • Apparently, there is an existing implementation of useDarkMode and it almost has 1k stars on GitHub, worth checking out.
logo with a rocket of the BigDevSoon application

Level up your Frontend skills

Code real-world projects based on Figma designs.
spread the word
Did you like this post? Share it with the world! 🌐