Back

从 Jotai 到 TanStack Store

Published on 19th July 2024

Jotai 是我过去使用最多的 React 状态管理库,但是我最近在逐渐迁移至 TanStack Store,并让它成为新项目的首选。

如果你有 Jotai 的使用经验,能帮助你更好地理解文章内容。

在应用开发中,我们希望过程是简单的。当应用变大,跨组件共享状态变得繁杂,利用全局状态管理器,可以简化开发并提高效率。

以下是 Jotai 的最简单示例:

import { atom, useAtomValue, useSetAtom } from "jotai";

const countAtom = atom(0);

function App() {
  const setCount = useSetAtom(countAtom);

  const increment = () => {
    setCount((prev) => prev + 1);
  };

  return (
    <div>
      <Counter />
      <button onClick={increment}>+</button>
    </div>
  );
}

function Counter() {
  const count = useAtomValue(countAtom);
  return <div>count: {count}</div>;
}

在该示例中,我们只能在 React 中访问并更新 countAtom。即便 Jotai 提供了在 React 之外的使用方式,但它必须在合适的地方(通常是 Application 顶层)包裹提供的 Provider

再来看 TanStack Store 的示例代码:

import { Store, useStore } from "@tanstack/react-store";

const countStore = new Store(0);

const increment = () => {
  countStore.setState((prev) => prev + 1);
};

function App() {
  return (
    <div>
      <Counter />
      <button onClick={increment}>+</button>
    </div>
  );
}

function Counter() {
  const count = useStore(countStore);
  return <div>count: {count}</div>;
}

increment 函数与 React 无关,相当简洁,无需包裹 Provider。更重要的是,Tanstack Store 是与框架无关的状态库,附带适用于 React、Svelte、Solid、Vue 和 Angular 等主流框架的适配器,这点在 Astro 中相当方便。以下是两个不同框架计数器之间共享状态的示例:

Hello, I'm Svelte counter

count: 0

Hello, I'm SolidJS counter

count: 0