Blog>
Snippets

Setting Up TanStack Store in React

Demonstrate how to integrate TanStack Store into a React application, focusing on initializing the store and creating a simple state.
import { createStore } from '@tanstack/react-store';
Importing createStore function from TanStack Store to initialize our store.
const initialState = { counter: 0 };
Defining the initial state of our application. In this case, a simple counter.
const store = createStore({
    initialState
});
Initializing the store with the predefined initial state.
import { useStore } from '@tanstack/react-store';
Importing useStore hook to allow our components to interact with the store.
const CounterComponent = () => {
    const [state, setState] = useStore(store);

    return (
        <div>
            <p>{state.counter}</p>
            <button onClick={() => setState(old => ({ ...old, counter: old.counter + 1 }))}>Increment</button>
        </div>
    );
};
Creating a simple CounterComponent that interacts with our store. It displays the counter and has a button to increment it.