Loading Skeleton in React

Tamal Chowdhury
by Tamal Chowdhury
Published on: June 11, 2024

React Suspense lets you show a loading indicator while your component data is being loaded (from a server)

Here, I am rendering a blog page with Nextjs and fetching the blog post data from a WordPress REST API.


I created a loading skeleton using some <div>’s and the TailwindCSS ‘animate-pulse’ class.

Now with Nextjs, you can easily create a loading indicator just by creating a `loading.tsx` page and dropping it into your page’s root folder.

However, when you do this your entire page waits for the data.

What if you only want the loading skeleton to show up on certain parts of the page? and not the entire page!

You can do this by moving data fetching to a child component and then wrap it inside the <Suspense/> like this:

<Suspense fallback={<LoadingPosts />}>
<HomeLatestPosts />
</Suspense>

Here: the component will load <HomeLatestPosts /> when data is loaded and use the <LoadingPosts /> as a fallback.

Pretty clean don’t you think?

Sharing is Caring: