CodingNic

Persistence & Application Preferences

Persist the Theme Preference

Persistence & Application Preferences 20 min read

Persist the Theme Preference

Task

Store the user’s selected theme in localStorage.

Open

Open:

js/ui.js

Create a theme storage key:

javascript
const THEME_KEY = 'calculator-theme';

When the theme changes, save it:

javascript
function saveTheme(theme) {
  localStorage.setItem(THEME_KEY, theme);
}

Then load the saved theme at startup:

javascript
function loadTheme() {
  return localStorage.getItem(THEME_KEY) || 'dark';
}

Apply the value using the theme mechanism already prepared by the starter:

javascript
const theme = loadTheme();
document.documentElement.dataset.theme = theme;

When the theme toggle changes the theme, call:

javascript
saveTheme(nextTheme);

Use the existing theme classes, attributes, or toggle logic from the starter rather than changing the CSS.

Test

  1. Switch between light and dark mode.
  2. Refresh the page.
  3. Confirm the selected theme remains active.
  4. Clear the site’s local storage and confirm the application falls back to its default theme.

Checkpoint

Both calculation history and the user’s theme preference now survive a page refresh.