Skip to content

Instantly share code, notes, and snippets.

@zhyd1997
Created September 15, 2021 05:37
Show Gist options
  • Save zhyd1997/f79549b6c3ee42feb7e493cc16846cce to your computer and use it in GitHub Desktop.
Save zhyd1997/f79549b6c3ee42feb7e493cc16846cce to your computer and use it in GitHub Desktop.
The following code tries to implement the React Suspense API

3 core issues

  1. mixin useEffect: the order should be
  • Start fetching
  • Start rendering
  • Finish fetching
  1. missing Suspense fallback
  2. not try to read user info before it loaded

I also add lazy reload component here.

import React from "react";
const UserProfile = ({ data }) => {
// Try to read user info, although it might not have loaded yet
const data = data.read();
return (
<>
<h1>{data.name}</h1>
<h2>{data.email}</h2>
</>
);
};
export default UserProfile;
import React, { Suspense } from 'react';
// Lazy-loaded
const UserProfile = React.lazy(() => import("./UserProfile"));
const SuspensefulUserProfile = ({ userId }) => {
// This is not a Promise. It's a special object from our Suspense integration.
const data = fetchUserProfile(userId);
// Show a spinner while the profile is loading
return (
<Suspense fallback={<Spinner />}>
<UserProfile data={data} />
</Suspense>
);
};
const UserProfileList = () => (
<>
<SuspensefulUserProfile userId={1} />
<SuspensefulUserProfile userId={2} />
<SuspensefulUserProfile userId={3} />
</>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment