💾 Persist Handler Demo

Demonstrating automatic signal persistence with localStorage and sessionStorage

Basic Signal Persistence

Values automatically saved to localStorage and restored on page load:

Text Input Persistence

Current value:

💡 Try typing, then refresh the page!

Counter with Reset Button

Counter persists across page reloads, but reset clears both display and storage:

Persistent Counter

Count:

Session Storage (Tab-Only)

This data is only saved for this browser tab and cleared when the tab closes:

Session-Only Data

Session value:

🔄 Refresh this tab: data persists

🆕 Open in new tab: data doesn't persist

Selective Signal Persistence

Choose which signals to persist and which to keep temporary:

Mixed Persistence

Persistent Score:

Temporary Lives:

💡 Reload the page: score persists, lives reset to 3

Theme Toggle with Persistence

Toggle between light and dark themes - your preference is remembered:

Theme Preferences

Current theme:

🔄 Your theme choice persists across page reloads!

New API Features

Demonstrating different persistence patterns:

Disabled Persistence

Temp counter:

This counter will reset on every page reload (persistence disabled).

Custom Storage Key

App Version:

User Preference:

These values use a custom storage key: 'starhtml-persist-myapp'

Session-Only Specific Signal

Tab ID:

Page views:

Only tabId persists in this tab session. Page views reset every reload.

Storage Management

Tools to manage and debug your persisted data:

Clear Storage

⚠️ These actions will only clear StarHTML persist data from this demo

How Persistence Works

The persist handler uses a two-phase approach for optimal performance:

🔧 Persistence Options

  • ds_persist("*") - Persist all signals in localStorage
  • ds_persist("signal1,signal2") - Persist specific signals only
  • ds_persist("*", session=True) - Use sessionStorage (tab-only)
  • ds_persist("*", key="mykey") - Use custom storage key
  • Preprocessing phase updates data-signals before Datastar init
  • Runtime phase handles dynamic updates and saves
  • MutationObserver catches dynamically added elements

⚡ Performance Features

  • Debounced writes to prevent excessive storage calls
  • Automatic cleanup of old or invalid data
  • JSON serialization for complex data types
  • Error handling for storage quota exceeded
  • Fallback behavior when storage is unavailable
  • Memory-efficient signal watching

🚀 Two-Phase Architecture

  • Phase 1: onGlobalInit preprocesses elements before Datastar
  • MutationObserver intercepts data-persist elements early
  • Updates data-signals attributes with stored values
  • Phase 2: onLoad handles runtime persistence
  • Watches for signal changes and saves to storage
  • Significantly reduces flash on slow connections