Next Showcase

by Jakkrit Turner

Loading

Zustand Theme

The theme switching (light & dark) feature that I created requires nothing more than just toggle a CSS class. It's light, efficient, and easy to implement. Moreover, we can add more themes freely and not tied to only light and dark color palettes.

You can try switching themes using the toggle button on the top right of the screen.

Let's explore the strategy:

1. Unified State with Zustand

I chose Zustand as my preferred state management library for this minimal system. It allows for highly performant component-level consumption without the pain to setup boilerplate like Redux that is pretty excessive for this use case.

2. Client-Side Persistence

To ensure a consistent user experience with theme preference (e.g., light, dark, or system), I use persist from Zustand Middleware. This feature automatically saves the user's last selection to local storage ensuring their preferred theme loads instantly on subsequent visits.

3. The Triple-Threat Logic: Handling System Preference

The core complexity is in the system mode. When the user selects System, the application needs to determine the effective theme. So I implemented a utility function (getEffectiveTheme) that demonstrates knowledge of advanced browser APIs. It checks the window.matchMedia("(prefers-color-scheme: dark)") API. This is the official way to detect the user's operating system preference, ensuring the website respects their global settings right at the start. Moreover, it correctly handles the Next.js Server-Side Rendering (SSR) environment by checking for the window object's existence, preventing critical hydration errors by returning a safe default theme during server rendering.

Next Showcase

by Jakkrit Turner