Blog>
Snippets

Integrating TanStack Store with TypeScript for Type-Safe State Management

Illustrate how to integrate TanStack Store with TypeScript, leveraging type-safe patterns to enforce more reliable and maintainable state management practices.
import { createStore } from 'tanstack-store';

// Define the state shape with a TypeScript interface
interface TodoState {
  todos: { id: number; text: string; completed: boolean }[];
}

// Initial state adhering to the TodoState interface
const initialState: TodoState = {
  todos: []
};

// Create the store with initial state
export const todoStore = createStore<TodoState>(initialState);
This piece of code demonstrates how to create a new TanStack Store for managing the state of todos in a TypeScript application. It first imports the createStore function from the 'tanstack-store' package. Then, it defines the shape of the application's state using a TypeScript interface named TodoState. Next, it declares an initialState variable that adheres to the TodoState interface structure. Finally, it creates and exports a new store named todoStore with the specified initial state, ensuring that the store's state structure is type-safe.
// Use the store in a component
import { useState } from 'react';
import { todoStore } from './store';

function TodoComponent() {
  const [todos, setTodos] = useState(todoStore.getState().todos);

  // Example of a function to add a todo
  function addTodo(todoText: string) {
    const newTodo = { id: Date.now(), text: todoText, completed: false };
    todoStore.setState((state) => ({
      todos: [...state.todos, newTodo]
    }));
    setTodos(todoStore.getState().todos);
  }

  return (
    <div>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </div>
  );
}
This code snippet shows how to use the previously created todoStore in a React functional component with TypeScript. It imports useState hook from 'react' and the todoStore from its definition file. The component, TodoComponent, uses the useState hook to hold and render the list of todos. It demonstrates a function addTodo that takes a string, creates a new todo item, updates the store with the new state, and finally updates the component's local state to reflect the changes. This example combines the reactive power of React's hooks with the type-safe, centralized state management provided by TanStack Store.