Blog>
Snippets

React Query Integration for Server State Management

Show how to integrate React Query for handling server state, data fetching, and caching mechanisms within a Next.js application.
import { useQuery } from 'react-query';

// Define a function to fetch data from your API
const fetchPosts = async () => {
  const response = await fetch('/api/posts');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};

// Use the useQuery hook to fetch and cache the data
function Posts() {
  const { data, error, isLoading } = useQuery('posts', fetchPosts);

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

  return (
    <ul>
      {data.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default Posts;
This code uses the useQuery hook from React Query to fetch, cache, and display posts in a Next.js application. It first defines a fetchPosts function to call the API and fetch posts. Then, it uses the useQuery hook, which automatically fetches data in the background and provides status flags like 'isLoading' and 'error' to handle loading states and errors.
import { QueryClient, QueryClientProvider } from 'react-query';
import Posts from './Posts';

// Initialize a new QueryClient instance
const queryClient = new QueryClient();

function App() {
  return (
    // Provide the QueryClient to the rest of your application
    <QueryClientProvider client={queryClient}>
      <Posts />
    </QueryClientProvider>
  );
}

export default App;
This code snippet sets up React Query's QueryClient and QueryClientProvider to be used in a Next.js application. The QueryClient is created and then provided to the entire application via the QueryClientProvider, which wraps the Posts component where the useQuery hook is used.