Next.js Discord

Discord Forum

The loader component doesn't display, instead the app freezes 1-2 seconds before loading the page

Answered
Thrianta posted this in #help-forum
Open in Discord
ThriantaOP
https://www.cheflink.live/recipes
When I navigate to the recipes, I'm having a 1-2 seconds delay before loading the page. It just freezes for 1-2 seconds.
It loads the queries from the CockroachDB database during that 1-2 seconds.
I even have a loading.js component.
export default async function Recipe({ params }) {
  const recipes = await listRecipes({ slug: params.slug });
  const recipe = recipes[0];
  const comments = await listComments({ recipeId: BigInt(recipe.id) });
  const users = await listUsers();

  const star =
    Math.round(
      (comments.reduce((accu, curr) => {
        if (curr.recipeId === recipe.id) {
          return accu + curr.rating;
        }
      }, 0) /
        comments.filter((c) => c.recipeId === recipe.id).length) *
        10
    ) / 10;

  const reviews = comments.reduce((accu, curr) => {
    if (curr.recipeId === recipe.id) {
      return accu + 1;
    }
  }, 0);

  return ( ...

For example these are the recipe page fetches.
I mean it doesn't matter if it loads 1 or 5 seconds, it just freezes there instead of displaying the loading.js component.

  return (
    <html className="bg-white" lang="en">
      <body
        className={`${lato.className} flex min-h-screen flex-auto flex-col`}
      >
        <AuthProvider user={user}>
          <Header comments={comments} recipes={recipes} />
          <Suspense fallback={<Loading />}>{children}</Suspense>
          <Footer />
        </AuthProvider>
        <Container />
      </body>
    </html>
  );
This is the layout, where I declare the suspense and loading components
Answered by joulev
(or just use loading.js normally and forget about all these Suspense's)
View full answer

9 Replies

explaining is hard so i'll give you an example
https://github.com/joulev/debug/tree/nextjs-loading-and-suspense-Yunus clone this branch, build it and try it locally
it has /correct which uses loading.js which works
/also-correct which uses a manual Suspense which also works
and /incorrect which also uses a manual Suspense but the Suspense is put in the wrong place like your case, hence is triggered at the wrong time
basically the problem is that your Suspense is triggered during the first load to any of your pages and is never triggered again after that
you need to use that Suspense inside the page.tsx of the dynamic page itself to trigger it whenever that page is visited
(or just use loading.js normally and forget about all these Suspense's)
Answer
@joulev (or just use `loading.js` normally and forget about all these `Suspense`'s)
ThriantaOP
Just adding loading.js to recipe directory solved the problem
Thanks