Subscribe to store state
A component needs a reactive value from a TanStack Store.
TanStack · Hook
useStore reads a value from a TanStack Store source, optionally selecting a slice and defining comparison behavior. In React, it is a deprecated alias for useSelector.
In TanStack Store React, useStore reads a store or derived value and optionally applies a selector to produce the value used by the component. It is a deprecated alias for useSelector, and the selected result can optionally be compared with a custom comparison function.
function useStore<TSource, TSelected>(source, selector?, compare?): TSelected;| Name | Type | Description |
|---|---|---|
source | TSource | The store-like source whose snapshot is observed. |
selector | (snapshot) => TSelected | Optional function receiving the snapshot and returning the selected value. |
compare | (a, b) => boolean | Optional function comparing the previous and next selected values. |
TSelected
import { useStore } from '@tanstack/react-store'
function Counter({ counterStore }) {
const count = useStore(counterStore, (state) => state.count)
return <span>{count}</span>
}Selects and renders the counter value from a TanStack Store instance.
A component needs a reactive value from a TanStack Store.
A component should consume only one field from a larger snapshot.
A selected value needs custom equality behavior.
useStore accepts a source, an optional selector, and an optional comparison function. It returns the selected value, or the source value when no selector is supplied.
Follow-up: What should new code use instead? Use useSelector, because the documentation marks useStore as its deprecated alias.
The source is the store-like object being observed, the selector maps its snapshot to the value the component needs, and compare can determine whether two selected values are equal.
Follow-up: Why select a smaller value? Selecting only the required slice can avoid making a component depend on unrelated state changes.
The hook returns TSelected. TSelected defaults to the source's type when no selector is provided, so the returned value reflects either the selected snapshot or the complete source value.
Follow-up: How can selection behavior be customized? Pass a selector and, when needed, a comparison function for selected values.
useSelectoruseAtomcreateStore