useContextより簡単!2025年Reactの状態管理はTanStack Storeで決まり

TanStack StoreはTanStackシリーズのライブラリ内部で使われている状態管理ライブラリです。
まだバージョン0でドキュメントもスカスカですが、十分使用実績があるといえます。
TanStack Storeの特徴は、
- セットアップ不要
- useStateと同じように使える
- reselect / useSelector / selectAtom といったメモ化処理が不要(!)
となっており、reduxやzustand、jotaiなどの著名状態管理ライブラリは言うに及ばず、useContext + useState を採用したパターンよりも簡単です。
インストール
npm install @tanstack/react-store
使い方
1. アプリケーションステートの作成
Store
のコンストラクタに状態として管理したいオブジェクトを渡します。
import { Store } from "@tanstack/react-store";
export const counterStore = new Store({ counter: 0, message: 'foo',});
2. 値の読み出し
useStore
フックを使い、先ほど定義したストアから現在の状態を得ます。その状態から参照したい値を取り出して返します。
import { useStore } from "@tanstack/react-store";import { counterStore } from "./counter"; // counterStoreを定義したファイルのパス
const count = useStore(counterStore, (store) => store.counter);
3. 値の更新
ストアのsetState
メソッド呼び出します。使い方は React.useState
のセッターと同じです。
ここで count
を更新しても message
は変わっていないので、message
を参照している他のコンポーネントは再描画されません。
counterStore.setState((state) => { return { ...state, count: state.count + 1, };});
以上のように簡単に使えます。 特に手動のメモ化処理が必要ないところがとても楽です。
ただ、TanStack StoreについてTannerさんに実戦で使えるのかどうか聞いたところ、“depends.” と言っていたので、場合によっては今後APIの変更などあるかもしれません。
その場合も下記のようにあらかじめカスタムフックにしておけば簡単に対応できると思います。
import { Store, useStore } from "@tanstack/react-store";
const counterStore = new Store({ counter: 0, message: 'foo',});
const setCounter = () => { counterStore.setState((store) => { return { ...store, count: store.count + 1, }; });};
// カスタムフックexport const useCounter = (): [number, typeof setCounter] => [ useStore(counterStore, (store) => store["count"]), setCounter,];
なんにせよとにかく楽すぎるので積極的に使っていきたいライブラリです。