Lưu trữ

Có thể khôi phục giá trị của named store vào bộ nhớ trình duyệt.


Tùy chọn lưu trữ

Nếu bỏ qua tùy chọn lưu trữ, sẽ tái sử dụng alias lưu trữ hiện có với name đó, nếu không có alias thì trong bộ nhớ.là giá trị mặc định. Hãy chỉ định lưu trữ khi cần persistence.

ts
type RxStateStorage =
  | "in-memory"
  | "auto"
  | "indexeddb"
  | "IndexedDB"
  | "websql"
  | "WebSQL"
  | "localstorage"
  | "localStorage"
  | "sessionstorage"
  | "sessionStorage";

Tên lưu trữ chữ thường có thể được sử dụng dưới dạng hình thức mặc định và các bí danh cho IndexedDB, WebSQL, localStorage, sessionStorage cũng được chuẩn hóa thành cùng một backend.

ts
createRxState(0, "count");
// alias가 없으므로 in-memory

createRxState(0, "count", { storage: "auto" });
// 같은 name이어도 storage가 다르면 별도 store

createRxState(0, "theme", { storage: "localstorage" });
createRxState("", "draft", { storage: "sessionstorage" });
createRxState("", "draftAlias", { storage: "sessionStorage" });

sessionstorage

sessionstorage và sessionStorage sử dụng sessionStorage của trình duyệt. Giá trị được giữ trong phạm vi tab/session hiện tại và sẽ được hydrate nếu được tạo lại với cùng một tên và tùy chọn lưu trữ.

tsx
const { setDraft, useDraft } = createRxState(
  "",
  "draft",
  { storage: "sessionStorage" },
);

function DraftInput() {
  const draft = useDraft();

  return (
    <input
      value={draft}
      onChange={(event) => setDraft(event.target.value)}
    />
  );
}

Ví dụ lưu trữ cài đặt người dùng

Ví dụ dưới đây lưu trữ UI preference. localStorageSau khi làm mới, nếu được tạo lại với cùng name và tùy chọn lưu trữ, sẽ hydrate giá trị đã lưu.

tsx
const { setPrefs, usePrefs, prefsReady } = createRxState(
  { compact: false, showHints: true },
  "prefs",
  { storage: "localstorage" },
);

function PreferencesPanel() {
  const prefs = usePrefs();

  return (
    <button onClick={() => setPrefs((prev) => ({ ...prev, compact: !prev.compact }))}>
      compact: {String(prefs.compact)}
    </button>
  );
}
© 2026 Byeolnaerim. Bảo lưu mọi quyền.Giới thiệuChính sách xử lý thông tin cá nhân