Reputation: 1
I am from React background. React application servers entire website on first request and then uses useEffect() hook for data fetching. I heard that Next.js also do the same thing. But my doubts are:
How and what files Next.js serves. Whether it servers only requested page or entire web application(all pages)?
If it serves entire web app, then how it fetches data when we route to some page which uses getServerSideProps?
Upvotes: 0
Views: 2811
Reputation: 1
Finally I got the answer!
Docs: https://nextjs.org/docs/basic-features/data-fetching#only-runs-on-server-side
When you request this page on client-side page transitions through next/link or next/router, Next.js sends an API request to the server, which runs getServerSideProps. It’ll return JSON that contains the result of running getServerSideProps, and the JSON will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have getServerSideProps defined.
Upvotes: 0
Reputation:
React is client side, getStaticProps
is for SSG (server side generation) and only called on static page generation (or on revalidate), getServerSideProps
is for SSR (server side rendering) and it will rerender the entire page on each request and probably serve it with something like renderToNodeStream
from react-dom/server
after which it will hydrate
it client side.
getServerSideProps
will be called once the request hits the server, then you can fetch your data in there, return it from there, after which it will be passed as props to your page component, which will then get rendered server side and passed to the client.
Alternatively you don't need to do everything server side, if you just want to fetch data like normal, using the useEffect
that you're used to, you can still do it like always, it'll also execute client side like always. In that case it will just rerender the component itself client side and not the whole page.
You should use getServerSideProps
if you actually want the request to reach the server and to regenerate the whole page using data from that function. If you just want to fetch data client side then do it like always.
Upvotes: 1