Blog>
Snippets

Optimizing State Updates to Prevent Unnecessary Re-renders

Provide examples on how to structure state updates in TanStack Store to ensure app performance by preventing unnecessary re-renders.
import { useStore } from 'tanstack-react-store';

// Custom hook to select a portion of the state
function useTodoItem(id) {
  return useStore(state => state.todos.find(todo => todo.id === id));
}
This code defines a custom hook using TanStack Store's `useStore` to select and return a specific todo item from the state. By selecting only the necessary piece of state, we prevent components that use this hook from re-rendering unless the specific todo item changes, optimizing performance.
const TodoItem = ({ id }) => {
  const todo = useTodoItem(id);
  // Render only the necessary item
  return <div>{todo.text}</div>;
};
This component uses the `useTodoItem` hook to render only the necessary todo item. It automatically benefits from the store's efficient update and subscription mechanism, minimizing re-renders to when the specific item's state changes.
setState(oldState => ({
  ...oldState,
  todos: oldState.todos.map(todo =>
    todo.id === updatedTodo.id ? { ...todo, ...updatedTodo } : todo
  )
}));
This pattern for updating the state ensures immutability by creating a new state object and updating only the todo that has changed. It avoids unnecessary re-renders of components that rely on other parts of the state.
// Assuming we have a function `toggleTodo` to update todo's completion status
function toggleTodoCompletion(id) {
  setState(oldState => ({
    ...oldState,
    todos: oldState.todos.map(todo =>
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    )
  }));
}
This code illustrates an efficient way to toggle a todo item's completion status. By using an immutable update pattern, it ensures only components subscribed to the changed todo item re-render.