Three problems with this code:
SuspensefulUserProfile
is not correctly utilizing the Suspense. We need to fetch data as we render, instead of first rendering and then fetching (through useEffect).UserProfile
component should be responsible for fetching the data instead ofSuspensefulUserProfile
.- There is no fallback component. This will lead to a poor user experience.
Corrected:
import { Suspense, useState, useEffect } from 'react';
const SuspensefulUserProfile = ({ userId }) => {
return (
<Suspense fallback={<h1>Loading profile...</h1>}>
<UserProfile userId={userId}/>
</Suspense>
);
};
const UserProfile = ({ userId }) => {
// Assuming fetchUserProfile gives the correct output. Not exactly a promise.
const user = fetchUserProfile(userId);
return (
<>
<h1>{user.name}</h1>
<h2>{user.email}</h2>
</>
);
};
const UserProfileList = () => (
<>
<SuspensefulUserProfile userId={1} />
<SuspensefulUserProfile userId={2} />
<SuspensefulUserProfile userId={3} />
</>
);