Blog>
Snippets

Migrating Redux State to TanStack Store

Demonstrate the process of migrating a slice of Redux state to TanStack Store, focusing on preserving the state shape and reimplementing selectors.
import { createStore } from '@tanstack/react-store';

// Definition of the initial state previously managed by Redux
const initialState = {
    counter: 0 // Example state slice
};

// Creating the store with the initial state
export const store = createStore({
    state: initialState
});
This code initializes the TanStack Store with an initial state that was previously managed by Redux. In this example, we're migrating a counter state slice.
import { useStore } from '@tanstack/react-store';

// Selector function similar to Redux's `useSelector`
function useCounterState() {
    const counter = useStore(state => state.counter);
    return counter;
}
This segment demonstrates how to create a selector with TanStack Store to access the state. The `useCounterState` function mimics the behavior of Redux's `useSelector` hook, allowing components to access the counter slice of the state.
import { store } from './store';

// Function to increment the counter, similar to dispatching an action in Redux
function incrementCounter() {
    store.setState(prevState => ({
        counter: prevState.counter + 1
    }));
}
Here we define a function to update the state, equivalent to dispatching an action in Redux. The `incrementCounter` function directly mutates the state using `store.setState`, which accepts a callback function with the previous state as an argument, returning the new state.