How to Properly Use Suspense in React 18
React 18 now supports data fetching with Suspense, but many people are still using the old approach. Here's a quick summary:
- Old way: Managing loading with useEffect + useState
- Improved way: Declarative handling with Suspense + fetch or SWR
Example code:
<Suspense fallback={<Loading />}>
<UserProfile userId={id} />
</Suspense>
This way, even if you call fetch directly inside the component, Suspense will automatically handle the loading state.
Note: You should also use ErrorBoundary for error handling. Additionally, to enable concurrent mode, you need to migrate to createRoot.
4 answers
Agreed. I found out about it last year too, but when I tried to apply it to a project, my teammates all stuck to the old methods, so I can't switch it up lol.
But when fetching data with Suspense, doesn't the screen go white if you don't wrap it with an ErrorBoundary? Please add some error handling to the example too.
This is right lol. Once you escape the useEffect hell, the amount of code is cut in half. The downside is that there's a bit of an initial learning curve.
Well... it's convenient when used with SWR, but I remember struggling with Suspense getting tangled up with hydration in server-side rendering (Next.js). Streaming SSR still feels like it hasn't been fully stabilized.