Blog>
Snippets

Performance Optimization in State Updates

Provides an example of efficiently updating complex nested state structures in TanStack Store to avoid performance bottlenecks.
import { useStore } from 'tanstack-react-store';

// Define an action to update nested state efficiently
const updateNestedState = (newData) => (state) => {
  // Assuming state has a deeply nested structure like state.data.users[userId].tasks[taskId]
  // Use functional updates to efficiently update deep nested structures without affecting other parts
  state.data.users[newData.userId].tasks[newData.taskId] = newData.taskInfo;
};
This code snippet showcases how to define an action using TanStack Store's 'useStore' hook for efficiently updating a deeply nested state structure. It uses a functional update pattern allowing for minimal re-rendering by directly targeting the nested item that needs updating. This approach is crucial for avoiding performance bottlenecks when working with complex state.
// Usage example
const userId = 'user123';
const taskId = 'task456';
const taskInfo = { completed: true, title: 'Finish documentation' };
const newData = { userId, taskId, taskInfo };

// Call the action defined above
useStore.getState().dispatch(updateNestedState(newData));
This piece of code provides a practical example of using the previously defined 'updateNestedState' action. It demonstrates how to dispatch an update to a deeply nested state structure, targeting a specific user's task and marking it as completed. This method efficiently updates the state without unnecessary re-renders of unaffected state parts.