Persisted State
persist(...) is one of Regor’s highest-leverage features:
- Turn any ref into persistent state with one call.
- It returns the same ref instance, so it can be used inline in context creation.
- State is restored from
localStorageon startup.
Why it matters
Section titled “Why it matters”For static-first sites with dynamic islands, persist lets each island keep user state without extra storage wiring.
Typical persisted states:
- Auth/session display model.
- Profile UI preferences.
- Theme, locale, and layout options.
- Last-opened tabs, filters, and panel state.
Real-world sample: header + preferences
Section titled “Real-world sample: header + preferences”import { createApp, persist, ref, sref } from 'regor'
createApp( { // Persisted auth/profile island state auth: persist( sref({ loggedIn: false, name: '', avatar: '', }), 'app:auth', ),
// Persisted UI preferences prefs: persist( sref({ theme: 'dark', locale: 'en', compact: false, }), 'app:prefs', ),
// Persisted primitive ref notifCount: persist(ref(0), 'app:notif-count'), }, { element: document.querySelector('#topbar-island')!, },)<header> <button r-if="!auth.loggedIn">Login</button> <div r-else> <img :src="auth.avatar" :title="auth.name" /> <span r-text="auth.name"></span> </div>
<select r-model="prefs.theme"> <option value="dark">Dark</option> <option value="light">Light</option> </select>
<button @click="notifCount = notifCount + 1"> Notifications: <span r-text="notifCount"></span> </button></header>After reload, previous values are restored automatically.
Inline context creation pattern
Section titled “Inline context creation pattern”Because persist returns the same ref, this is valid and recommended:
const context = { theme: persist(ref('dark'), 'app:theme'), filters: persist(sref({ status: 'open', query: '' }), 'app:filters'),}Behavior details
Section titled “Behavior details”- If stored JSON exists, ref is hydrated from storage.
- If stored JSON is invalid, Regor logs warning and rewrites storage with current ref value.
- If key is empty,
persistthrows. - Updates are synced via reactive observation.
Key strategy
Section titled “Key strategy”Use namespaced keys:
app:authapp:prefspage:search:filters
Avoid collisions across islands/features.