Blog>
Snippets

Initializing the Store and Defining State

Showcase how to initialize TanStack Store in a React application, defining initial state structure and types for a todo list application.
import { createQueryClient, QueryClientProvider } from '@tanstack/react-query';

// Initialize QueryClient
const queryClient = createQueryClient();
This code imports the required functions from the TanStack Query library and initializes the Query Client. This client will be used to manage queries and cache within the React application.
import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './App';

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);
This snippet wraps the entire React application with the QueryClientProvider, passing the previously created queryClient as a prop. This enables all components within the App to use the functionalities provided by TanStack Query.
import { useQuery } from '@tanstack/react-query';

function fetchTodos() {
  return fetch('https://example.com/todos').then(res => res.json());
}

export function useTodos() {
  return useQuery(['todos'], fetchTodos);
}
Defines a custom hook `useTodos` that uses `useQuery` to fetch the todo list from an API. The query is identified by a unique key `['todos']`, which can be used for caching and invalidating the query if necessary.
function TodoList() {
  const { data: todos, isLoading, error } = useTodos();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}
This component utilizes the custom hook `useTodos` to fetch and display a list of todos. It handles loading and error states, rendering a list of todos if the fetch is successful.