คู่มือฉบับสมบูรณ์: React's use Resource Hook | MLOG | MLOG}> {/* Assuming this ID doesn't exist and will cause an error */} ); } export default App;

ในตัวอย่างนี้ หากฟังก์ชัน fetchUser โยนข้อผิดพลาด (เช่น เนื่องจากสถานะ 404) คอมโพเนนต์ ErrorBoundary จะดักจับข้อผิดพลาดและแสดง UI สำรอง ซึ่ง fallback สามารถเป็นคอมโพเนนต์ React ใดก็ได้ เช่น ข้อความแสดงข้อผิดพลาดหรือปุ่มลองอีกครั้ง

เทคนิคขั้นสูงกับ use:

1. การแคช (Caching) ทรัพยากร

เพื่อหลีกเลี่ยงการดึงข้อมูลซ้ำซ้อน คุณสามารถแคชทรัพยากร (Promise) และนำกลับมาใช้ใหม่ในหลายๆ คอมโพเนนต์หรือการเรนเดอร์ได้ การปรับปรุงประสิทธิภาพนี้มีความสำคัญอย่างยิ่ง

            
import React, { Suspense, useRef } from 'react';

const resourceCache = new Map();

async function fetchUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (!response.ok) {
    throw new Error(`Failed to fetch user: ${response.status}`);
  }
  return response.json();
}

function getUserResource(userId) {
  if (!resourceCache.has(userId)) {
    resourceCache.set(userId, {
      read() {
        if (!this.promise) {
          this.promise = fetchUser(userId);
        }
        if (this.result) {
          return this.result;
        }
        throw this.promise;
      }
    });
  }
  return resourceCache.get(userId);
}

function UserProfile({ userId }) {
  const resource = getUserResource(userId);
  const user = resource.read();

  return (
    

{user.name}

Email: {user.email}

Phone: {user.phone}

); } function App() { return ( Loading user data...
}> ); } export default App;

ในตัวอย่างนี้:

2. การใช้ use: กับ Server Components

Hook use: มีประโยชน์อย่างยิ่งใน React Server Components ซึ่งสามารถทำการดึงข้อมูลได้โดยตรงบนเซิร์ฟเวอร์ ส่งผลให้การโหลดหน้าเว็บครั้งแรกเร็วขึ้นและปรับปรุง SEO ได้ดีขึ้น

ตัวอย่างกับ Next.js Server Component

            
// app/user/[id]/page.jsx (Server Component in Next.js)
import React from 'react';

async function fetchUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (!response.ok) {
    throw new Error(`Failed to fetch user: ${response.status}`);
  }
  return response.json();
}

export default async function UserPage({ params }) {
  const user = React.use(fetchUser(params.id));

  return (
    

{user.name}

Email: {user.email}

Phone: {user.phone}

); }

ใน Next.js server component นี้ ฟังก์ชัน fetchUser จะดึงข้อมูลผู้ใช้บนเซิร์ฟเวอร์ Hook use: จะระงับคอมโพเนนต์จนกว่าข้อมูลจะพร้อมใช้งาน ซึ่งช่วยให้การเรนเดอร์ฝั่งเซิร์ฟเวอร์ (server-side rendering) มีประสิทธิภาพ

แนวทางปฏิบัติที่ดีที่สุดสำหรับ use:

ตัวอย่างการใช้งานจริง

1. รายการสินค้า E-commerce

ลองนึกภาพเว็บไซต์ E-commerce ที่แสดงรายการสินค้า การ์ดสินค้าแต่ละใบสามารถใช้ use: เพื่อดึงรายละเอียดของสินค้าได้:

            
// ProductCard.jsx
import React, { Suspense } from 'react';

async function fetchProduct(productId) {
  const response = await fetch(`/api/products/${productId}`);
  if (!response.ok) {
    throw new Error(`Failed to fetch product: ${response.status}`);
  }
  return response.json();
}

function ProductCard({ productId }) {
  const product = React.use(fetchProduct(productId));

  return (
    

{product.name}

{product.description}

Price: ${product.price}

); } function ProductList({ productIds }) { return (
{productIds.map((productId) => ( Loading product...
}> ))}
); } export default ProductList;

แนวทางนี้ช่วยให้มั่นใจได้ว่าการ์ดสินค้าแต่ละใบจะโหลดอย่างอิสระต่อกัน และการเรนเดอร์หน้าเว็บโดยรวมจะไม่ถูกบล็อกโดยสินค้าที่โหลดช้า ผู้ใช้จะเห็นตัวบ่งชี้การโหลดแยกกันสำหรับแต่ละสินค้า ซึ่งมอบประสบการณ์ที่ดีกว่า

2. ฟีดโซเชียลมีเดีย

ฟีดโซเชียลมีเดียสามารถใช้ use: เพื่อดึงโปรไฟล์ผู้ใช้ โพสต์ และความคิดเห็นได้:

            
// Post.jsx
import React, { Suspense } from 'react';

async function fetchPost(postId) {
  const response = await fetch(`/api/posts/${postId}`);
  if (!response.ok) {
    throw new Error(`Failed to fetch post: ${response.status}`);
  }
  return response.json();
}

async function fetchComments(postId) {
  const response = await fetch(`/api/posts/${postId}/comments`);
  if (!response.ok) {
    throw new Error(`Failed to fetch comments: ${response.status}`);
  }
  return response.json();
}

function Comments({ postId }) {
  const comments = React.use(fetchComments(postId));

  return (
    
    {comments.map((comment) => (
  • {comment.text}
  • ))}
); } function Post({ postId }) { const post = React.use(fetchPost(postId)); return (

{post.title}

{post.content}

Loading comments...
}>
); } export default Post;

ตัวอย่างนี้ใช้ Suspense boundaries ซ้อนกันเพื่อโหลดเนื้อหาของโพสต์และความคิดเห็นอย่างเป็นอิสระต่อกัน ผู้ใช้สามารถเห็นเนื้อหาของโพสต์ในขณะที่ความคิดเห็นยังคงกำลังโหลดอยู่

ข้อผิดพลาดที่พบบ่อยและวิธีหลีกเลี่ยง

ทางเลือกอื่นนอกจาก use:

แม้ว่า use: จะมีประโยชน์อย่างมาก แต่ก็มีแนวทางอื่นในการดึงข้อมูลใน React:

การเลือกระหว่างทางเลือกเหล่านี้ขึ้นอยู่กับความซับซ้อนของแอปพลิเคชันและข้อกำหนดเฉพาะของคุณ สำหรับสถานการณ์การดึงข้อมูลที่ไม่ซับซ้อน use: อาจเป็นตัวเลือกที่ยอดเยี่ยม สำหรับสถานการณ์ที่ซับซ้อนมากขึ้น ไลบรารีเช่น useSWR หรือ React Query อาจเหมาะสมกว่า

สรุป

Hook use: ใน React เป็นวิธีการที่ทรงพลังและเป็นแบบ declarative สำหรับการจัดการโหลดทรัพยากรและการดึงข้อมูล การใช้ประโยชน์จาก use: ร่วมกับ Suspense จะช่วยให้คุณลดความซับซ้อนของตรรกะในคอมโพเนนต์ ปรับปรุงประสบการณ์ผู้ใช้ และเพิ่มประสิทธิภาพการทำงาน คู่มือนี้ได้ครอบคลุมพื้นฐาน เทคนิคขั้นสูง และแนวทางปฏิบัติที่ดีที่สุดสำหรับการใช้ use: ในแอปพลิเคชัน React ของคุณ การปฏิบัติตามแนวทางเหล่านี้จะช่วยให้คุณสามารถจัดการการทำงานแบบอะซิงโครนัสได้อย่างมีประสิทธิภาพ และสร้างแอปพลิเคชันที่แข็งแกร่ง มีประสิทธิภาพสูง และเป็นมิตรต่อผู้ใช้ ในขณะที่ React ยังคงพัฒนาต่อไป การเรียนรู้เทคนิคอย่าง use: ให้เชี่ยวชาญจึงเป็นสิ่งสำคัญเพื่อที่จะก้าวทันและมอบประสบการณ์ผู้ใช้ที่ยอดเยี่ยม

แหล่งข้อมูลอ้างอิง