How to detect if the user prefers dark mode

One of the best things you can do to improve the User experience on your web app or website is to adjust your website's look and feel as per the user's preference.


Usually while coding I have number of tabs open - and most of the times wherever possible I switch to dark mode, including my code editor theme. So while switching between the tabs / applications, suddenly when I am faced with a white background, it kinda strains my eyes.


So in general, I tend to stick longer on the websites that offer dark mode and I love a website even more when I visit it the first time and it automatically defaults to dark mode. This can be achieved using the browser api prefers-colors-scheme.


Using this api, you can detect the user's color scheme preference and default your site to the preferred theme. If your app is built on react, you can easily do this by adding this check in the useEffect hook.

useEffect(() => {
  window.matchMedia('(prefers-color-scheme: dark)') ? setTheme('dark') : setTheme('light');
}, [])