Blog>
Snippets

Integrating TanStack Config with React

Provide an example of how to seamlessly integrate TanStack Config with a React project, including setup steps and configuration options.
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';

export default function fetchData() {
  // Use React Query's useQuery hook to fetch data
  const { isLoading, error, data } = useQuery(['dataKey'], fetchDataFunction);

  if (isLoading) return 'Loading...';

  if (error) return 'An error has occurred: ' + error.message;

  return (
    <div>
      <h1>Data</h1>
      <p>{data}</p>
    </div>
  );
}
This snippet shows how to use the TanStack React Query to fetch data within a React component. `useQuery` is used to perform the data fetching, handling loading states, and errors seamlessly.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

// Create a client
const queryClient = new QueryClient();

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
This code block sets up the QueryClient from TanStack React Query and provides it to the React app using the QueryClientProvider. This is essential for initializing React Query in your application.