Initializing a TanStack Store in a React Application
Show how to create and initialize a TanStack Store within a React application to manage global state.
import { createStore } from '@tanstack/react-store';
First, you need to import the createStore function from the @tanstack/react-store package.
const store = createStore({
initialState: {
counter: 0
}
});
Then, initialize your store with an initial state. In this example, we have a simple counter state.
import { useStore } from '@tanstack/react-store';
function Counter() {
const [state, setState] = useStore(store);
return (
<div>
<p>Counter: {state.counter}</p>
<button onClick={() => setState(old => ({...old, counter: old.counter + 1}))}>Increment</button>
</div>
);
}
Finally, you can use your store within a React component. Here, we're creating a Counter component that displays the state's counter value and provides a button to increment it.