Skip to content

Instantly share code, notes, and snippets.

@talhatahir
Created February 28, 2021 16:30
Show Gist options
  • Save talhatahir/212dcaf845a6a618d2c0dee14bba0d1b to your computer and use it in GitHub Desktop.
Save talhatahir/212dcaf845a6a618d2c0dee14bba0d1b to your computer and use it in GitHub Desktop.
Correct way to use React Suspense
/*
1. The first issue is that Suspense requires a fallback prop which can be a React Component to be shown to the user as a fallback while the original component
in Suspense loads. The code is missing the fallback Prop.
2. The second issue is that this code is rendering components first and then fetching which actually is not how Suspense is used, Suspense is used to fetch data
and render the component all at the same time.
3. For Suspense to work correctly, the fetchUserProfile API call should be similar to React Relay which allows a user to read bits and chunks of data as it
becomes available. At the moment, fetchUserProfile looks more like a simple API returning a prmoise which will not work with Suspense.
*/
//Fixed code with some code cleaning
// I am assuming by the looks of it that UserProfileList is the component which gets called by this React Application.
import { Suspense, useState } from 'react';
const initialResource = fetchUserProfile(1); //to start fetching ASAP
const [resource, setResource] = useState(initialResource);
const SuspensefulUserProfile = ({ userId }) => {
setResource(fetchUserProfile(userId));
return <UserProfile />;
};
const UserProfile = () => {
const user = resource.user.read();
return (
<>
<h1>{user.name}</h1>
<h2>{user.email}</h2>
</>
);
};
const UserProfileList = () => (
<>
<Suspense fallback={<h1>Loading profile...</h1>}>
<SuspensefulUserProfile userId={1} />
</Suspense>
<Suspense fallback={<h1>Loading profile...</h1>}>
<SuspensefulUserProfile userId={2} />
</Suspense>
<Suspense fallback={<h1>Loading profile...</h1>}>
<SuspensefulUserProfile userId={3} />
</Suspense>
</>
);
const rootElement = document.getElementById('root');
ReactDOM.createRoot(rootElement).render(<UserProfileList />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment