Introducing React Suspense and Error Boundaries
In the previous section, we used the isLoading
state from TanStack Query to show a loading message when the posts are still being fetched. While this works fine, handling loading states like that can get a bit messy. A better way to model loading states is to use React Suspense. React Suspense is a special component that can display a fallback until its children have finished loading. To use React Suspense, data fetching frameworks and libraries need to support it. Thankfully, TanStack Query supports Suspense. Frameworks like Relay and Next.js support it as well.
Setting up a Suspense Boundary
To use Suspense, we need to define a Suspense Boundary with a fallback. If any child component within the boundary is fetching data, the fallback will be rendered in place of the boundary, replacing all the child components of it. When all data is fetched successfully, all child components will be rendered. This allows us to write code...