Creating a Reactive UI Component with TanStack Store
Showcase the creation of a React component that consumes global state from TanStack Store and re-renders automatically upon state changes.
import { createStore } from '@tanstack/store-react';
// Create a store with an initial state
cost counterStore = createStore({
initialState: { count: 0 },
});
First, we import the createStore function from @tanstack/store-react and create a new store named counterStore with an initial state where count is set to 0.
import { useStore } from '@tanstack/store-react';
function Counter() {
// Subscribe to store changes
const count = useStore(counterStore, state => state.count);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => counterStore.setState(state => ({ count: state.count + 1 }))}>Increment</button>
</div>
);
}
We define a functional React component named Counter that uses the useStore hook to subscribe to changes in the counterStore. This subscription specifically listens to changes in the count attribute of the store's state. The component renders the current count and provides an 'Increment' button to update the count.