0Pricing
Next.js 15 Fullstack Web Apps · บทเรียน

React Query สำหรับสถานะเซิร์ฟเวอร์

จัดการการดึงข้อมูลฝั่งเซิร์ฟเวอร์ การแคช และการทำข้อมูลให้ตรงกันด้วย React Query (TanStack Query)

React Query สำหรับสถานะเซิร์ฟเวอร์ เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack Web Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

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

Meet React Query

React Query, now known as TanStack Query, is a powerful library for managing server-side state in your applications.

It helps you fetch, cache, synchronize, and update data in your React and Next.js apps effortlessly. Think of it as your data layer, handling the complexities of server data so you don't have to.

Benefits of TanStack Query

React Query solves many common data fetching challenges, making your app feel faster and more responsive:

  • Caching: Stores fetched data to prevent unnecessary requests.
  • Revalidation: Automatically refreshes stale data in the background.
  • Loading States: Provides clear indicators for data fetching status.
  • Error Handling: Simplifies managing and displaying fetch errors.
  • Performance: Reduces network requests and improves user experience.

Initial Setup: Provider

To use React Query, you first need to set up a QueryClient and provide it to your app. This is typically done at the root of your application, wrapping your components with QueryClientProvider.

Here's how you might set up the client and provider in a Next.js app:

/* app/providers.jsx (or similar) */
"use client";
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';

const queryClient = new QueryClient();

export default function AppProviders({ children }) {
  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}

Your First Data Fetch

The useQuery hook is the core for fetching data. It takes two main arguments: a unique query key and an async query function.

The query key identifies your data in the cache. The query function actually fetches it. Try running this simple example fetching a user:

"use client";
import { useQuery } from '@tanstack/react-query';
import React from 'react';

async function fetchUser() {
  const res = await fetch(
    'https://jsonplaceholder.typicode.com/users/1'
  );
  if (!res.ok) throw new Error('Failed to fetch');
  return res.json();
}

export default function UserProfile() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', 1],
    queryFn: fetchUser,
  });

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

  return (
    <div>
      <h3>User: {data.name}</h3>
      <p>Email: {data.email}</p>
    </div>
  );
}

Power of Query Keys

Query keys are crucial! They are like unique IDs for your cached data. React Query uses them to identify, refetch, and invalidate specific queries.

  • Keys can be simple strings (e.g., 'todos') or arrays.
  • Arrays are great for passing dependencies or parameters, like ['todos', { status: 'active' }].
  • When a key's array elements change, React Query knows to refetch the data.

UI Feedback for Users

useQuery returns several useful states to manage your UI and provide feedback to users:

  • isLoading: true when the query is first fetching data.
  • isError: true if the query failed to fetch data.
  • data: The successfully fetched data, or undefined.
  • error: The error object if isError is true.

These allow you to show loading spinners or error messages.

"use client";
import { useQuery } from '@tanstack/react-query';
import React from 'react';

async function fetchPost(id) {
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${id}`
  );
  if (!res.ok) throw new Error('Fetch failed');
  return res.json();
}

export default function PostDetail() {
  const postId = 2; // Example ID
  const { data, isLoading, isError, error } = useQuery({
    queryKey: ['post', postId],
    queryFn: () => fetchPost(postId),
  });

  if (isLoading) return <p>Loading post {postId}...</p>;
  if (isError) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h4>Post {data.id}</h4>
      <p>{data.title}</p>
    </div>
  );
}

Smart Caching Behavior

React Query automatically caches data after a successful fetch. By default, data is considered "stale" immediately after fetching, meaning it might be refetched in the background when the component mounts or the window regains focus.

This "stale-while-revalidate" approach provides instant UI feedback with fresh data updates. You can configure staleTime to keep data "fresh" for longer, preventing unnecessary refetches.

Updating Server Data

While useQuery is for fetching, useMutation is for creating, updating, or deleting data on the server (e.g., POST, PUT, DELETE requests).

It provides a mutate function to trigger the server call, and also returns isPending (similar to isLoading), isError, and data for the mutation itself. Let's see an example of creating a new todo:

"use client";
import { useMutation } from '@tanstack/react-query';
import React from 'react';

async function addTodo(newTodo) {
  const res = await fetch(
    'https://jsonplaceholder.typicode.com/todos',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newTodo),
    }
  );
  if (!res.ok) throw new Error('Failed to add');
  return res.json();
}

export default function AddTodo() {
  const mutation = useMutation({
    mutationFn: addTodo,
    onSuccess: (data) => alert('Added: ' + data.title),
    onError: (error) => alert('Error: ' + error.message),
  });

  const handleAdd = () => {
    mutation.mutate({ title: 'New task', completed: false });
  };

  return (
    <div>
      <button onClick={handleAdd} disabled={mutation.isPending}>
        {mutation.isPending ? 'Adding...' : 'Add Todo'}
      </button>
    </div>
  );
}

Keeping Cache Fresh

After a mutation (e.g., adding a new item), your cached list of items might be outdated. You can use queryClient.invalidateQueries() to mark relevant queries as stale, which triggers a refetch for those queries.

This ensures your UI always reflects the latest server data. You typically call invalidateQueries in the onSuccess callback of useMutation.

"use client";
import { useMutation, useQueryClient } from '@tanstack/react-query';
import React from 'react';

async function createItem(newItem) {
  const res = await fetch(
    'https://jsonplaceholder.typicode.com/posts',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newItem),
    }
  );
  if (!res.ok) throw new Error('Failed to create');
  return res.json();
}

export default function CreateItemButton() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: createItem,
    onSuccess: () => {
      // Invalidate 'items' query to refetch the list
      queryClient.invalidateQueries({ queryKey: ['items'] });
      alert('Item created and list will refetch!');
    },
  });

  const handleClick = () => {
    mutation.mutate({ title: 'New Item', body: '...' });
  };

  return (
    <button onClick={handleClick} disabled={mutation.isPending}>
      {mutation.isPending ? 'Creating...' : 'Create Item'}
    </button>
  );
}

Beyond the Basics

React Query offers many more advanced features to build highly performant and user-friendly data experiences:

  • Optimistic Updates: Update UI before server response for instant feedback.
  • Pagination/Infinite Queries: Efficiently load large datasets.
  • Dependent Queries: Fetch data based on results of another query.
  • Query Devtools: A browser extension for inspecting cache and queries.

Query Hook Check

You've learned about useQuery and useMutation.

Which of the following statements about React Query hooks are TRUE?

Lesson Summary

In this lesson, we explored React Query (TanStack Query), a powerful library for managing server state. You learned how to:

  • Set up the QueryClientProvider.
  • Fetch data using the useQuery hook with query keys.
  • Handle loading and error states for a better UX.
  • Mutate data on the server with useMutation.
  • Keep your cache fresh by invalidating queries after mutations.

React Query significantly simplifies data fetching and synchronization, making your Next.js apps faster and more robust!

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

บทเรียน “React Query สำหรับสถานะเซิร์ฟเวอร์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “React Query สำหรับสถานะเซิร์ฟเวอร์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “React Query สำหรับสถานะเซิร์ฟเวอร์”

จัดการการดึงข้อมูลฝั่งเซิร์ฟเวอร์ การแคช และการทำข้อมูลให้ตรงกันด้วย React Query (TanStack Query) คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “React Query สำหรับสถานะเซิร์ฟเวอร์” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. React Query สำหรับสถานะเซิร์ฟเวอร์
  2. สถานะฝั่งไคลเอ็นต์ด้วย Zustand/Jotai
  3. กลยุทธ์การแคชฝั่งเซิร์ฟเวอร์
  4. การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ
← กลับไปที่ Next.js 15 Fullstack Web Apps