Trung BìnhState Management iconState Management

Cách tạo và sử dụng atom trong Jotai?

  • Primitive atom: const countAtom = atom(0) — trong component dùng useAtom(countAtom) trả về [value, setValue].
  • Derived read-only: const doubleAtom = atom(get => get(countAtom) * 2) — dùng useAtomValue.
  • Derived read-write: atom(get => get(baseAtom), (get, set, newVal) => set(baseAtom, newVal * 2)). atomWithStorage('key', defaultVal) từ jotai/utils tự đồng bộ localStorage, handle SSR hydration. atomWithDefault(get => get(otherAtom)) tạo atom có thể override nhưng mặc định derive.
  • Architecture Provider-less: Jotai dùng WeakMap lưu state theo atom object reference thay vì string key như Recoil — atoms tự nhiên unique, hỗ trợ code-split, không lo duplicate key. useAtomValue (chỉ đọc) và useSetAtom (chỉ ghi, không subscribe, không re-render) là hooks tối ưu performance.

Xem toàn bộ State Management cùng filter theo level & chủ đề con.

Mở danh sách State Management