Implementing a dark theme toggle with react-redux
It’s been a few years since dark mode became a popular feature of many websites, so I decided to write about how to implement it using react-redux. All code from this tutorial is available in this repository, And Here’s what we will build:
The Logic
We have a switch button that has two states: Sun and Moon. Sun Icon is for the light theme, while Moon Icon is for the dark theme. in this project, Redux solved a lot of problems for you, you could easily access data throughout the entire app without having to pass it through each component. Not only could you read this data, but you could also manipulate the state from anywhere in the app as well. and we have a config file that I define the theme properties for LIGHT and DARK themes, such as textColor, backgroundColor, borderColor, and so on. I also attached my basic theme objects for those two themes.
Note: you should use redux when You have a very large and complex app with multiple states that are needed in many places of the app and You have often refreshing states.
The Project Setup
I usually use yarn because it is a fast, reliable, and secure alternative to NPM. There are three things we need:
an actual store to hold the state
an action to dispatch intent
a reducer to handle that intent
an action type
That’s easy enough:
About Action You can think of an action as an event that describes something that happened in the application. here the action is changeTheme.
I Always handle any manipulate in Reduce section.
I use to keep action types separately because, In this way, you reduce the risk of accidentally misspelling one or more of the action types in one of the sources where they’re used. This will also prevent wasting a lot of time debugging a simple bug.
Now, to provide a theme
We need to tell our component(s) how to style themselves based on the current theme.
Let’s toggle
Great! Now all that is left, is to dispatch the changeTheme action whenever the icon is clicked.
Let’s take a closer look, we use the useSelector hook to get state from our store using a selector function.
All done!
Thanks for reading!
this post is already on https://atefe-dev.medium.com/implementing-a-dark-theme-toggle-with-react-redux-14ec197cbff7
Top comments (0)