Blog>
Snippets

Initializing the TanStack Store in a React Application

Show how to set up TanStack Store in a React project, including the installation process, creating a basic store, and using it within a React component.
// First, install TanStack Store using npm or yarn
npm install @tanstack/react-store
This line shows how to install TanStack Store in your project using npm. You can also use yarn if you prefer.
import { createStore } from '@tanstack/react-store';

// Create a basic store
const counterStore = createStore({
  id: 'counter',
  initialState: { count: 0 },
  actions: {
    increment(state) {
      state.count += 1;
    },
    decrement(state) {
      state.count -= 1;
    },
  },
});
This snippet demonstrates how to create a basic store with TanStack Store. The store manages a counter with increment and decrement actions.
import React from 'react';
import { useStore } from '@tanstack/react-store';

function Counter() {
  const [state, actions] = useStore(counterStore);

  return (
    <div>
      <p>{`Count: ${state.count}`}</p>
      <button onClick={actions.increment}>Increment</button>
      <button onClick={actions.decrement}>Decrement</button>
    </div>
  );
}

export default Counter;
This code example shows how to use the TanStack Store in a React component. It demonstrates accessing the store's state and actions within a functional component to manage a counter.