Comparing State Updates: Redux vs. TanStack Store
Demonstrate updating the state in both Redux and TanStack Store, highlighting the ease of use and readability of TanStack Store's API for updating nested state.
// Redux
import { createStore } from 'redux';
const initialState = { user: { name: 'John', age: 30 } };
function userReducer(state = initialState, action) {
switch (action.type) {
case 'UPDATE_AGE':
return {
...state,
user: { ...state.user, age: action.payload }
};
default:
return state;
}
}
const store = createStore(userReducer);
store.dispatch({ type: 'UPDATE_AGE', payload: 31 });
This code demonstrates updating nested state in Redux. It uses the createStore function to create a store with a userReducer. The reducer checks for an 'UPDATE_AGE' action and updates the 'age' property of the 'user' nested state using the action's payload. The state update requires spreading the existing state and user object to maintain immutability.
// TanStack Store (formerly React Query)
import { createStore } from '@tanstack/store';
const store = createStore({
user: { name: 'John', age: 30 }
});
store.update(draft => {
draft.user.age = 31;
});
This code snippet demonstrates updating nested state using TanStack Store, highlighting its simplicity and readability. The createStore function initializes the state, and the update method is used to modify the 'age' property of the 'user' directly using a draft state. This approach simplifies the process of updating nested state compared to Redux.