I'm struggling to find problems with using Suspense and React hooks.
There are several key problems with the React code below.
import { Suspense, useState, useEffect } from 'react';
const SuspensefulUserProfile = ({ userId }) => {
const [data, setData] = useState({});
useEffect(() => {
fetchUserProfile(userId).then((profile) => setData(profile));
}, [userId, setData])
return (
<Suspense>
<UserProfile data={data} />
</Suspense>
);
};
const UserProfile = ({ data }) => {
return (
<>
<h1>{data.name}</h1>
<h2>{data.email}</h2>
</>
);
};
const UserProfileList = () => {
<>
<SuspensefulUserProfile userId={1} />
<SuspensefulUserProfile userId={2} />
<SuspensefulUserProfile userId={3} />
</>
};
Let me know what they are.
I found two key problems.
- Misuse of
setdatainuseEffectdependency array - Didn't provide
suspensefallbackprops.
I think there is still one key problem remaining.
One weird thing is why userId needs to be included in the dependency array.
You misused
Suspenseto its core, at least until suspense for data fetching is available.Suspense only currently works with
React.lazycomponents, not with arbitrary 'loading' states of your application. For instance, how should React figure out that yourdatais loading?The only use for
Suspenseis to allow showing some fallback while React loads a lazy component. For other types of lazy loading app data you can implement your own fallback, as in: