Hook use: di React per le Risorse: Una Guida Completa | MLOG | MLOG}> {/* Supponendo che questo ID non esista e causi un errore */} ); } export default App;

In questo esempio, se la funzione fetchUser lancia un errore (ad esempio, a causa di uno stato 404), il componente ErrorBoundary catturerà l'errore e visualizzerà l'interfaccia di fallback. Il fallback può essere qualsiasi componente React, come un messaggio di errore o un pulsante per riprovare.

Tecniche Avanzate con use:

1. Caching delle Risorse

Per evitare recuperi ridondanti, puoi memorizzare nella cache la risorsa (Promise) e riutilizzarla tra più componenti o render. Questa ottimizzazione è cruciale per le prestazioni.

            
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 ( Caricamento dati utente...
}> ); } export default App;

In questo esempio:

2. Usare use: con i Server Components

L'hook use: è particolarmente utile nei React Server Components, dove il recupero dei dati può essere eseguito direttamente sul server. Ciò si traduce in caricamenti iniziali della pagina più veloci e una migliore SEO.

Esempio con un Server Component di Next.js

            
// 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}

); }

In questo server component di Next.js, la funzione fetchUser recupera i dati dell'utente sul server. L'hook use: sospende il componente finché i dati non sono disponibili, consentendo un rendering efficiente lato server.

Best Practice per use:

Esempi dal Mondo Reale

1. Elenco Prodotti E-commerce

Immagina un sito di e-commerce che mostra elenchi di prodotti. Ogni scheda prodotto può usare use: per recuperare i dettagli del prodotto:

            
// 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) => ( Caricamento prodotto...
}> ))}
); } export default ProductList;

Questo approccio garantisce che ogni scheda prodotto si carichi in modo indipendente e che il rendering complessivo della pagina non sia bloccato da prodotti a caricamento lento. L'utente vede indicatori di caricamento individuali per ogni prodotto, offrendo un'esperienza migliore.

2. Feed di un Social Media

Il feed di un social media può usare use: per recuperare profili utente, post e commenti:

            
// 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}

Caricamento commenti...
}>
); } export default Post;

Questo esempio usa confini di Suspense annidati per caricare il contenuto del post e i commenti in modo indipendente. L'utente può vedere il contenuto del post mentre i commenti si stanno ancora caricando.

Errori Comuni e Come Evitarli

Alternative a use:

Sebbene use: offra vantaggi significativi, esistono approcci alternativi al recupero dei dati in React:

La scelta tra queste alternative dipende dalla complessità della tua applicazione e dai tuoi requisiti specifici. Per scenari semplici di recupero dati, use: può essere un'ottima opzione. Per scenari più complessi, librerie come useSWR o React Query potrebbero essere più appropriate.

Conclusione

L'hook use: in React fornisce un modo potente e dichiarativo per gestire il caricamento delle risorse e il recupero dei dati. Sfruttando use: con Suspense, puoi semplificare la logica dei tuoi componenti, migliorare l'esperienza utente e ottimizzare le prestazioni. Questa guida ha coperto i fondamenti, le tecniche avanzate e le best practice per l'utilizzo di use: nelle tue applicazioni React. Seguendo queste linee guida, puoi gestire efficacemente le operazioni asincrone e creare applicazioni robuste, performanti e facili da usare. Man mano che React continua a evolversi, padroneggiare tecniche come use: diventa essenziale per rimanere all'avanguardia e offrire esperienze utente eccezionali.

Risorse