Tailwind CSS Course
Tailwind CSS
/
Advanced

Theme Switcher

Definition

The architectural pattern of combining the 'Class' strategy with the 'System' strategy, creating a 3-way toggle: Light, Dark, and System (Auto).

Explain Like I'm New

The holy grail of theming. You give the user a dropdown. If they pick 'Light', it forces Light. If they pick 'Dark', it forces Dark. If they pick 'System', it removes the forced class and goes back to secretly watching their macOS/Windows settings.

Real World Example

GitHub's exact appearance settings page. It gives you 3 options: 'Sync with system', 'Single theme: Light', and 'Single theme: Dark'.

Common Use Cases

  • •Professional SaaS applications
  • •User settings panels

Interactive Example

Interview Questions

basic

  • In a 3-way theme switcher, how do you reset the site back to 'System' mode after a user has manually forced 'Dark' mode?

intermediate

  • Why do you need to be careful about 'Flash of Unstyled Content' (FOUC) when building a React theme switcher?

Flash Cards

Question

How to reset to system?

Click to reveal answer
Answer

You remove the `theme` key from `localStorage` entirely, and remove the `dark` class from the `<html>` tag. The CSS media queries will naturally take over again.

Question

Why careful about FOUC?

Click to reveal answer
Answer

If React renders the Light page first, and then `useEffect` runs 100ms later to check `localStorage` and swap to Dark mode, the user will see a blinding white flash before it turns dark. The initial check must run synchronously in the `<head>` of the HTML.