Next.js Discord

Discord Forum

Components renders twice

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
I am new to next and tried to understand where server/client components run and when. I've created a simple application that calls /api to generate a number and display it to the client.
I've noticed that even though I'm only refreshing the page once, the component is rendered twice (And calls the API twice).

This is my component:
// page.tsx

export default async function HomePage() {
  console.log("==================");

  console.log("Fetching a");
  const data = await fetch("http://localhost:3000/api", {
    next: { revalidate: 2 },
  });
  const { a } = await data.json();
  
  console.log("Got a");

  return <div>{a}</div>;
}


And this is my route handler:
// route.ts

export async function GET(request: Request) {
  console.log("Called GET");
  await new Promise((r) => setTimeout(r, 3000));
  const rand = Math.random();

  console.log("Generated " + rand);
  return Response.json({ a: rand });
}


After running and accessing the page, this is what's printed to the console:
==================
Fetching a
Got a
Called GET
==================
Fetching a
Got a
Called GET
 ✓ Compiled /favicon.ico in 99ms (531 modules)
Generated 0.611595607287567
Generated 0.44314617780706156


Apart from being weird, I feel like it can cause error since the route handler is called twice and may cause duplicate mutations and so on.

I wanted to know if there is a reason for this or is this something related to the setup?
I tried setting Strict Mode to false but it did nothing.

8 Replies

Australian Freshwater Crocodile
I'm having the same issue, any way to debug, I tried to comment my middleware but it's still happening
my page is a server component, and my layout too
@Australian Freshwater Crocodile @Masai Lion try disabling react strict mode
Australian Freshwater Crocodile
@Arinji it's already disabled in my project
and won't this only prevent the double useEffect ? cause my component is a server component
Australian Freshwater Crocodile
I'm working on a reproducible case in a new project, I just wanted leads on ways to debug