Last active
February 2, 2021 23:43
-
-
Save danwoods/8720db908e4d65adbd17c153966bf5c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* There are 3 key problems with the React code below. Can you find them? | |
* Assume fetchUserProfile exists elsewhere. | |
*/ | |
import { Suspense, useState, useEffect } from 'react'; | |
const SuspensefulUserProfile = ({ userId }) => { | |
// Problem #1 - Using `useEffect` and `useState` like this can lead to a waterfall situation, negating the benefits of `Suspense` | |
// See - https://reactjs.org/docs/concurrent-mode-suspense.html#approach-1-fetch-on-render-not-using-suspense | |
const [data, setData] = useState({}); | |
useEffect(() => { | |
// Problem #2 - This looks like we're using `fetchUserProfile` as a normal Promise. Per the docs it should be wrapped and return a `read` function | |
// See - https://codesandbox.io/s/frosty-hermann-bztrp?file=/src/fakeApi.js:395-427 | |
fetchUserProfile(userId).then((profile) => setData(profile)); | |
// Problem #3 - Why do we care if `setData` changes? It's a function | |
}, [userId, setData]) | |
// Problem(?) #4 - <Suspense /> should probably have a `fallback` prop | |
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} /> | |
</> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment