0Pricing
tRPC End-to-End Type Safe APIs · บทเรียน

การผสานรวม React Query ขั้นสูง

ใช้ความสามารถอันทรงพลังของ React Query เช่น การดึงข้อมูลล่วงหน้า การทำให้ข้อมูลไม่ถูกต้อง และการดึงข้อมูลใหม่เบื้องหลังร่วมกับ tRPC

การผสานรวม React Query ขั้นสูง เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน tRPC End-to-End Type Safe APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Advanced React Query with tRPC

Welcome! In this lesson, we'll dive into advanced features of React Query that supercharge your tRPC applications.

You'll learn how to optimize user experience and ensure data freshness using powerful techniques like prefetching, query invalidation, and background refetching.

Improving UX with Prefetching

Prefetching is about fetching data before a user explicitly requests it. Imagine a blog list: when a user hovers over a post, you can prefetch the detailed post content.

  • Faster Navigation: Reduces loading times when users click a link.
  • Smoother Experience: Eliminates loading spinners on subsequent pages.
  • Anticipatory UI: Makes your app feel snappier and more responsive.

Prefetching tRPC Queries

React Query's queryClient.prefetchQuery allows you to fetch data and store it in the cache. With tRPC, you access the queryClient via trpc.useUtils().

This example simulates prefetching a list of posts when a component is rendered, perhaps on a homepage before a user clicks "View All Posts."

// A simplified demo for prefetching a tRPC query

// --- Mocks for demonstration purposes ---
const mockQueryClient = {
  prefetchQuery: async (queryKey, queryFn) => {
    console.log(`Prefetching: ${JSON.stringify(queryKey)}`);
    // Simulate API call
    const data = await queryFn();
    console.log(`Data for ${JSON.stringify(queryKey)} prefetched:`, data);
    return data;
  }
};

const trpc = {
  post: {
    list: {
      queryFn: async () => {
        // In a real app, this would be your tRPC query
        return new Promise(resolve => setTimeout(() => {
          resolve([{ id: 1, title: 'First Post' }, { id: 2, title: 'Second Post' }]);
        }, 100));
      }
    }
  },
  useUtils: () => ({
    queryClient: mockQueryClient
  })
};
// --- End Mocks ---

async function main() {
  console.log("Starting prefetch demo...");

  // In a React component, you'd call trpc.useUtils()
  const utils = trpc.useUtils();

  // Prefetch the 'post.list' query
  await utils.queryClient.prefetchQuery(
    ['post', 'list'], // tRPC query key
    trpc.post.list.queryFn // The actual fetch function
  );

  console.log("Prefetching complete. Data is now in cache.");
}

main();

Keeping Data Fresh with Invalidation

After you perform an action that changes data on your backend (like creating, updating, or deleting), your client-side cache might become outdated.

Query invalidation tells React Query that certain cached data is "stale" and needs to be refetched the next time it's accessed. This ensures your UI always shows the latest information.

Invalidating After tRPC Mutations

The most common use case for invalidation is after a mutation. When you create a new item, you want the list showing all items to update automatically.

You can use onSuccess callback of useMutation to invalidate related queries.

// A simplified demo for invalidating a tRPC query after a mutation

// --- Mocks for demonstration purposes ---
const mockQueryClient = {
  invalidateQueries: (queryKey) => {
    console.log(`Invalidating queries matching: ${JSON.stringify(queryKey)}`);
    // In a real app, this marks cached data as stale
  }
};

const trpc = {
  post: {
    create: {
      mutateFn: async (newPost) => {
        console.log(`Creating post: ${newPost.title}...`);
        return new Promise(resolve => setTimeout(() => {
          console.log("Post created on server.");
          resolve({ id: 3, ...newPost });
        }, 150));
      }
    }
  },
  useUtils: () => ({
    queryClient: mockQueryClient
  })
};

// Simulate a useMutation hook's logic
async function useCreatePostMutation() {
  const utils = trpc.useUtils();

  return {
    mutateAsync: async (newPost) => {
      const result = await trpc.post.create.mutateFn(newPost);
      // Invalidate the 'post.list' query to refetch it
      utils.queryClient.invalidateQueries(['post', 'list']);
      return result;
    }
  };
}
// --- End Mocks ---

async function main() {
  console.log("Starting invalidation demo...");

  const { mutateAsync } = await useCreatePostMutation();

  await mutateAsync({ title: 'My New Awesome Post' });

  console.log("Mutation complete and 'post.list' query invalidated.");
  console.log("Next time 'post.list' is fetched, it will be fresh.");
}

main();

Targeting Specific Queries

Sometimes you don't want to invalidate all queries of a certain type. You might want to invalidate a specific item, like a single post after it's been updated.

React Query uses query keys to identify cached data. You can invalidate queries based on exact keys or partial matches.

// Demo for granular invalidation

// --- Mocks ---
const mockQueryClient = {
  invalidateQueries: (queryKey) => {
    console.log(`Invalidating specific queries: ${JSON.stringify(queryKey)}`);
  }
};

const trpc = {
  post: {
    update: {
      mutateFn: async (postId, updates) => {
        console.log(`Updating post ${postId} with:`, updates);
        return new Promise(resolve => setTimeout(() => {
          console.log(`Post ${postId} updated.`);
          resolve({ id: postId, ...updates });
        }, 100));
      }
    }
  },
  useUtils: () => ({
    queryClient: mockQueryClient
  })
};

async function useUpdatePostMutation() {
  const utils = trpc.useUtils();

  return {
    mutateAsync: async (postId, updates) => {
      const result = await trpc.post.update.mutateFn(postId, updates);
      // Invalidate the specific post query by ID
      utils.queryClient.invalidateQueries(['post', 'byId', { id: postId }]);
      // You might also invalidate the list if the update affects it
      utils.queryClient.invalidateQueries(['post', 'list']);
      return result;
    }
  };
}
// --- End Mocks ---

async function main() {
  console.log("Starting granular invalidation demo...");
  const { mutateAsync } = await useUpdatePostMutation();
  const postIdToUpdate = 123;

  await mutateAsync(postIdToUpdate, { title: 'Updated Title' });

  console.log(`Queries for post ${postIdToUpdate} and post list invalidated.`);
}

main();

Automatic Background Refetching

React Query doesn't just refetch data when you manually invalidate it. It also has smart defaults for background refetching.

When a query becomes "stale" (its staleTime expires), React Query will automatically refetch it in the background under certain conditions, like:

  • When a component mounts.
  • When the window refocused.
  • When the network reconnects.

Customizing Refetch Behavior

You can control when data is considered stale using the staleTime option. By default, staleTime is 0, meaning data is immediately stale.

Setting a staleTime (e.g., 5 * 60 * 1000 for 5 minutes) means data won't be refetched for that duration, even if components remount or the window is refocused, improving performance.

// Demo for configuring staleTime globally

// --- Mocks ---
class QueryClient {
  constructor(options = {}) {
    this.defaultOptions = options.defaultOptions || {};
    console.log("QueryClient initialized with defaultOptions:", this.defaultOptions);
  }
  // Simplified method to show it would apply options
  fetchQuery(queryKey, queryFn, options = {}) {
    const effectiveStaleTime = options.staleTime !== undefined
      ? options.staleTime
      : (this.defaultOptions.queries && this.defaultOptions.queries.staleTime !== undefined
          ? this.defaultOptions.queries.staleTime
          : 0); // Default React Query staleTime
    console.log(`Fetching ${JSON.stringify(queryKey)} with staleTime: ${effectiveStaleTime}`);
    return queryFn(); // Simulate fetch
  }
}

// Simulating React Query's QueryClientProvider setup
function QueryClientProvider({ children, client }) {
  console.log("QueryClientProvider is setting up the client.");
  // In a real React app, 'client' would be available via context
  if (typeof children === 'function') {
    children(client); // Just call the child function for this demo
  }
}
// --- End Mocks ---

async function main() {
  console.log("Starting staleTime configuration demo...");

  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 1000 * 60 * 5, // 5 minutes
        refetchOnWindowFocus: false, // Disable refetch on window focus globally
      },
    },
  });

  QueryClientProvider({
    client: queryClient,
    children: async (client) => {
      // Simulate a tRPC query being made, which would inherit these options
      await client.fetchQuery(['myPost', 1], async () => {
        console.log("Simulating a fetch for 'myPost'.");
        return { id: 1, title: "Configured Post" };
      });
    }
  });

  console.log("QueryClient configured. Queries will respect 5 min staleTime.");
}

main();

A Full Workflow Example

Let's imagine a user flow combining these features:

  1. User lands on a dashboard. We prefetch data for upcoming sections.
  2. User clicks "Edit Profile." The profile data is already in cache (due to prefetching or a recent fetch).
  3. User updates their name. A mutation is triggered.
  4. Upon success, the profile query is invalidated.
  5. The UI automatically refetches in the background (due to invalidation and perhaps staleTime: 0 on the profile query), showing the new name without a full page reload or manual refresh.

React Query Features Quiz

Consider a tRPC application where you have a list of products and a form to add a new product.

Which combination of React Query features would you use to immediately update the product list after a new product is successfully added?

Summary of Advanced Features

Great job! You've learned how to leverage advanced React Query features to build highly performant and user-friendly tRPC applications.

  • Prefetching improves perceived performance by loading data early.
  • Query Invalidation ensures data freshness after mutations.
  • Background Refetching automatically updates stale data.

These techniques are crucial for professional-grade frontend development. Keep experimenting with them!

คำถามที่พบบ่อย

บทเรียน “การผสานรวม React Query ขั้นสูง” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การผสานรวม React Query ขั้นสูง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวม React Query ขั้นสูง”

ใช้ความสามารถอันทรงพลังของ React Query เช่น การดึงข้อมูลล่วงหน้า การทำให้ข้อมูลไม่ถูกต้อง และการดึงข้อมูลใหม่เบื้องหลังร่วมกับ tRPC คุณปฏิบัติ tRPC End-to-End Type Safe APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การผสานรวม React Query ขั้นสูง” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม

ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. tRPC กับตัวจัดเส้นทางแอปของ Next.js
  2. การผสานรวม React Query ขั้นสูง
  3. คอมโพเนนต์ฝั่งเซิร์ฟเวอร์และการดึงข้อมูลด้วย tRPC
  4. การอัปเดตเชิงมองโลกในแง่ดีด้วยการเปลี่ยนแปลงข้อมูลของ tRPC
← กลับไปที่ tRPC End-to-End Type Safe APIs