Blog>
Snippets

Migrating from Redux to TanStack Store

Provide a code snippet that demonstrates the process of migrating a simple Redux-based counter application to use TanStack Store, showcasing state initialization and dispatching actions.
// Redux implementation
import { createStore } from 'redux';

// Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

// Action Creators
export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });

// Reducer
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case DECREMENT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

// Store
const store = createStore(counterReducer);

// Usage
store.dispatch(increment());
console.log(store.getState());
This is a simple Redux-based counter implementation, including action types, action creators, a reducer for handling state updates, and the creation of the store. The final lines show how to dispatch an action and log the updated state.
// Migrating to TanStack Store
import { createStore } from '@tanstack/react-store';

// Initial state
const initialState = { count: 0 };

// Creating TanStack Store
const store = createStore({
  initialState,
  // Defining actions using reducers
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
    decrement: (state) => {
      state.count -= 1;
    }
  }
});

// Dispatching actions
store.dispatch(state => state.increment());
console.log(store.getState());
This code snippet shows how to migrate the previous Redux counter application to use TanStack Store. It illustrates defining the initial state, creating the store with actions as reducers, dispatching an action to update state, and logging the state.