πΎ Persistence β Save State Across Reloads β
Stunk provides state persistence with withPersistence
, allowing your state to be saved and restored even after a page refresh.
Enabling Persistence β
To persist a chunkβs state, wrap it with withPersistence
and provide a storage key:
typescript
import { chunk } from "stunk";
import { withPersistence } from "stunk/middleware";
const counterChunk = withPersistence(chunk({ count: 0 }), {
key: "counter-state",
});
// State automatically persists to localStorage
counterChunk.set({ count: 1 });
Using Different Storage Options β
By default, withPersistence
uses localStorage
, but you can switch to sessionStorage
, etc:
typescript
const sessionStorageChunk = withPersistence(chunk(0), {
key: "counter",
storage: sessionStorage, // Uses sessionStorage instead of localStorage
});
Custom Serialization & Encryption β
You can define custom serialization and deserialization to transform data before storing it:
typescript
const encryptedChunk = withPersistence(chunk({ secret: "1234" }), {
key: "encrypted-data",
serialize: (value) => encrypt(JSON.stringify(value)),
deserialize: (value) => JSON.parse(decrypt(value)),
});
Why Use Persistence? β
βοΈ Save user state across reloads
βοΈ Improve user experience by retaining settings
βοΈ Support custom storage and security methods
Next: Async Chunk β Handling Loading & Errors β‘
Learn how to manage asynchronous state with built-in loading and error handling! π