Device state (twinstate/device, a utility)
Some state belongs to one device only — a theme, whether a hint was seen, where you were scrolled in a thread. It has nothing to do with syncing, so it is not part of the core: nothing in the server, the protocol, the replica or the outbox depends on it, and an app can ignore this page entirely. The utility exists because every app adopting Twinstate needs the same small thing next to it: typed values, persisted, following other tabs.
ts
import { createDeviceState, device } from 'twinstate/device';
export const { useDevice, setDevice } = createDeviceState({
theme: device(z.enum(['light', 'dark']).default('light'), {
key: 'app-theme',
encoding: 'raw',
}),
hintSeen: device(z.boolean().default(false)), // key 'hintSeen', JSON
threadScroll: device(z.number().default(0), { perId: true }), // one value per record id
});
useDevice('theme');
setDevice('theme', 'dark');
useDevice('threadScroll', threadId); // perId: read one record's value
setDevice('threadScroll', threadId, 240); // …and write it- Declared in the client app only, never in the shared registry — the server has no reason to know it exists — and never synced.
- Keys and encodings are yours. Each entry names its storage key and its encoding (
jsonby default, orrawfor a plain string), so an app adopting the utility keeps the keys and values it already has on users' devices and in test fixtures. - Persisted in
localStorage, and follows other tabs of the same app through the browser'sstorageevent. Per-tab scratch state that must not follow other tabs belongs insessionStorage, outside it. - Independent of the client. It needs no
TwinProviderand no connection; its keys never collide with the outbox's or the cache's, which are namespaced by the core.
| tier | examples | API |
|---|---|---|
| UI | hover, a menu being open, a gesture | plain useState |
| device | theme, dismissed hints | useDevice / setDevice |
| shared | everything that should follow you | useShared / mutations |