Skip to main content
Data fetching cover image

Overview

This architecture provides a robust solution for data fetching in Next.js applications by combining Server Actions with TanStack Query. We use this in our Letraz’s client side code. Key features:
  • 🔄 Seamless server-side and client-side data fetching
  • 📦 Efficient caching and revalidation
  • 🛡️ Type-safe API interactions
  • 🚨 Comprehensive error handling
  • 🎯 Feature-based organization
  • ♾️ Built-in support for infinite scrolling
Please note that this documentation is tailored for the Letraz’s client side code and is an evolving document. The information provided here is subject to change based on the evolving requirements of the project.

Setup

Provider Setup

Core Types

/lib/config/api-types.ts

Project Structure

Implementation Details

API Client Configuration

/lib/config/api-client.ts

Custom React Query Hooks Example

Query Hooks

Mutation Hooks

Server Actions Integration

Error Handling

Query Key Management

Using Prefetched Data with Hydration

Key Concepts

  1. Prefetching Data: Fetch data on the server using TanStack Query’s queryClient.prefetchQuery.
  2. Hydration: Pass server-fetched data to the client using the dehydrate and Hydrate APIs.

Prefetch Data in a Page

In Next.js page (page.tsx), fetch data on the server and use dehydrate to serialize it for hydration:

Fetch Data with TanStack Query

Create a utility to fetch data:
In custom hook, use useQuery to access the hydrated data:

Optimistic Updates

1: Make a Server Action

2: Create a Custom Hook for Optimistic Updates

3: Make Reuseable Query Options

3: Use the Hook in a Component

For more details, refer to the following links.

Reference