React Dark Mode with Styled Theming and Context
How to toggle themes with React Hooks, context and styled components
Bring dark mode to your React apps
Dark mode is becoming more commonly supported in apps, both on the web and natively. React is in a great position to support such a feature, by leveraging the framework’s capabilities and packages readily available in the surrounding ecosystem. Toggling between a dark and light mode can be achieved very elegantly and modularly, as will be demonstrated here.
This article will walk through the entire process of setting up a dark mode for your app, and a means to toggle between a light
and dark
theme. The demo I designed for this talk is freely available on Github to aid in the reader’s understanding.
To achieve a dark mode and toggle function, the following tools will be used:
- React’s Context API. We will be defining a context specifically for managing theme toggling, that will be accessible anywhere in your app
- The
useContext
hook will be used specifically for getting our themetoggle()
function from the above context.useContext
gets the value of a provided context from anywhere in your component tree - The
useState
hook to persist whatmode
…