useDarkMode Hook in React
This hooks objective is to enable and disable the dark mode on-demand and store the current state using localStorage.
Also with useMedia,
we can check the user's browser preference for dark mode, so we can set a default.
We can sync state with localStorage
by using a useLocalStorage
hook. We can detect the user's dark mode preference by using a useMedia
hook. Both of these hooks can be used in other situations, but here we're using them to create a useful hook in relatively few lines of code.
With useMediaQuery,
we can check the user's browser preference for dark mode. Then, with useLocalStorage
, we can initialize, store, and persist the current state (dark or light mode) in localStorage.
import { useEffect } from 'react';
import useMediaQuery from './useMediaQuery';
import useLocalStorage from './useLocalStorage';export default funciton useDarkMode() {
const defaultDarkMode = useMediaQuery(
['(prefers-color-scheme: dark)'],
[true],
false
);
};
Finally, with this hook, we can add or remove a class dark
to the body
element. Now we can access it across the entire application. This will let us change styles and colors with ease.