Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why component is called twice in Next.js?

Tags:

next.js

This is my pages/index.js of my next.js project

const Index = () => {
  console.log('Index Component Called');
  return (
    <div>Hello</div>
  )
}

export default Index;

The console log function is called twice on CLIENT side and one time on next.js node SERVER

like image 604
Namdev Avatar asked Jan 22 '20 12:01

Namdev


1 Answers

I guess because Pages in next.js are server side rendered (or pre-rendered).
So in this case when next.js is rendering your page(server side), the script will console.log("Index Component Called") then on your frontend react it's hydrating so all the code coming from the server should be executed again.
In next.js you can execute Server Side code inside getInitialProps, and in pages only not components.

like image 151
Nico Avatar answered Sep 23 '22 16:09

Nico