useStorage
Read and persist JSON-serializable state scoped to a single widget instance, with a React useState-style API that survives app restarts and macOS reboots.
Signature#
SIGNATURE
function useStorage<T>(
key: string,
defaultValue: T
): [T, (next: T | ((prev: T) => T)) => void]
Parameters#
keystringRequired- Storage key within this widget instance (automatically isolated from other placed instances).
defaultValueTRequired- Initial JSON-serializable value used before any value has been written.
Return Value#
valueTTuple [0]- Current stored value, read synchronously on the very first frame with no flicker.
setValuefunctionTuple [1]- Persists the next value to disk; accepts either a direct value
setValue(next)or an updatersetValue(prev => next).
Example: Daily Habit Counter with Automatic Day Rollover#
TSX
import React, { Button, HStack, Spacer, Text, VStack, useStorage, useWidget } from "deskset-react";
interface HabitRecord {
day: string;
done: number;
}
function todayISO(): string {
const d = new Date();
return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
}
export default function HabitTracker() {
const { theme, t, isPreview } = useWidget();
const [record, setRecord] = useStorage<HabitRecord>("habit", {
day: todayISO(),
done: 0,
});
const today = todayISO();
const count = isPreview ? 3 : (record.day === today ? record.done : 0);
const increment = () => {
setRecord((prev) => {
const base = prev.day === today ? prev.done : 0;
return { day: today, done: base + 1 };
});
};
return (
<VStack
maxWidth={true}
maxHeight={true}
padding={16}
spacing={10}
background={theme.isPure ? "clear" : "theme.card"}
cornerRadius={theme.isPure ? 0 : theme.corner}
clip={!theme.isPure}
>
<Text fontSize={13} color="theme.secondary">{t("今日打卡", "Daily Check-in")}</Text>
<Text fontSize={32} fontWeight="bold" monospacedDigits>{`${count}`}</Text>
<Spacer />
<HStack spacing={8}>
<Button title={t("打卡 +1", "+1")} variant="filled" color="theme.accent" onClick={increment} />
<Button icon="arrow.counterclockwise" variant="tinted" onClick={() => setRecord({ day: today, done: 0 })} />
</HStack>
</VStack>
);
}
Limits & Lifecycle#
- Per-instance isolation: Two desktop copies of the same widget maintain independent storage namespaces.
- Size limits: Up to 256 KiB per key and 512 KiB total per widget instance.
- Preserved on hot reload: Editing source in Widget Studio and reinstalling the same package ID keeps all stored data intact; data is removed only when the widget instance is deleted from the desktop.
- Preview safety: Writes are ignored while
isPreview === true.