Detecting Dark Mode With React Hooks
It feels like practically every website and app supports dark mode these days. The feature has been widely adopted, partially because the traditional CSS implementation is quite simple.
Luckily you can keep it all in sync with a simple React hook.
The CSS Way
Dark mode is traditionally implemented by using the prefers-color-scheme media query to invert colors when dark mode is active.
Using CSS is nice because the media query dynamically changes in response to the appearance mode the user chooses in the system preferences:
No event listeners or complex stuff... just a media query.
The React Hook Way
Alright... so how do we do this in React? Three simple steps:
- Read the initial value of the media query on mount
- Add a change event listener to the prefers-color-scheme media query
- Store the theme name with useState
This is the full hook! No additional dependencies are required.
The hook exports:
- The current themeName
- Helpful isDarkMode and isLightMode booleans
Which can be easily consumed by any component: