Essentials about Suspense and Error Boundaries | by Vladimir Topolev | Oct, 2023

[ad_1]

We go through the main concepts of Suspense and ErrorBoundaries and highlight what they have in common and what the difference is. Also, we find out about such patterns in React for fetching data: Fetch-On-Render and Render-As-You-Fetch and why we’re talking about it in the context of Suspense.

Photo by Lautaro Andreani on Unsplash

Content:
Fetch-On-Render pattern
How React behaves when React component throws Error, Promise
React.lazy and Suspense
Render-As-You-Fetch pattern

Do you know how to fetch data in the React component? Definitely, you know, since you do it every day as a ReactJS developer. I even know what pattern comes to your mind first. It should look like this:

const ContainerComponent = ({userId}) => {
const [user, setUser] = useState(null);

useEffect(() => {
fetchUserInfo(userId)
.then((fetchedUser) => setUser(fetchedUser))
}, []);

if(user === null) {
return <p>Loading data</p>
}

return <UserInfo user={user}>
}

Was I right?

We all love patterns, and it’s our vocabulary that helps us convey ideas and understand each other. Do you know the name of this one? You may come up with your own name—for example, the pattern of fetching data in React components. You are right, but it is not precise.

This pattern is called Fetch-On-Render.

It is a self-explanatory name:

👉 The Fetch-On-Render pattern assumes that the data retrieval is initiated only after the component has been rendered on the screen.

It is a well-known and straightforward pattern, and there’s nothing to add.

[ad_2]

Source link