Question presented to candidate: "Add a dark mode toggle to our site. On a first visit it should follow the operating system setting. If the user flips the toggle, remember their choice across reloads. Give them a way to go back to following the system. Bonus points if the page never flashes the wrong theme."
Requirements:
- A toggle that switches between light and dark, applied to the whole page (an attribute on
<html>plus CSS variables). - First visit: follow
prefers-color-scheme, and keep following it live if the OS setting changes. - An explicit choice is saved to
localStorageand wins over the OS setting after a reload. - A "Use system setting" action that forgets the saved choice.
- Accessible toggle semantics; storage and
matchMediafailures must not crash the app.
What a strong answer should cover:
- The state model: a stored choice (
light,darkorsystem) plus the live OS preference; the applied theme is derived from the two. window.matchMedia("(prefers-color-scheme: dark)")with achangelistener, cleaned up on unmount.- Persisting only the explicit choice, wrapped in try/catch.
- Applying the theme with a
data-themeattribute and CSS custom properties, pluscolor-schemefor native controls. - The flash of the wrong theme and the fix: a tiny inline script in
<head>that sets the attribute before first paint.
Clarifying questions expected:
- "Two states or three: is 'follow the system' a choice the user can return to?"
- "Is the app server-rendered? That changes how we avoid the flash."
- "Should the choice sync across open tabs?"
Code / implementation expected: Yes. A hook, composable or service plus a toggle, roughly 60-90 lines.