Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS, _app, SSG, getInitialProps vs getStaticProps and how am I supposed to stick to DRY?

I know that the topic isn't new and I found (and read) a few discussions. What I couldn't find is an answer to my still remaining question.

How do others work around the problem of not being able to use getStaticProps in _app.js ? getInitialProps is not an option for me cause I want to use SSG. Is there a way to force SSG even when using getInitialProps? Or do I really have to fetch all my data from my Headless CMS on every page? Since I want to build a Header (including Navigation) and a Footer, for example. Currently the only option I see is to repeat a lot of code.

Any hints much appreciated and thanks for reading!

like image 532
SMEETT Avatar asked Oct 12 '20 15:10

SMEETT


People also ask

Can I use getStaticProps in _APP?

You can use getInitialProps within the _app. js file. Unfortunately, this disables automatic static optimization across the entire application.

What is difference between getInitialProps and getServerSideProps?

Is there a difference between getInitialProps and getServerSideProps ? The main difference between the legacy getInitialProps and the newer getServerSideProps is how the function is used during transitions, when users click on a Link to visit different parts of your site.

What is difference between getStaticProps and getServerSideProps?

getStaticProps(): A method that tells the Next component to populate props and render into a static HTML page at build time. getServerSideProps(): A method that tells the Next component to populate the props and render into a static HTML page at run time.

Is getInitialProps deprecated?

Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .


1 Answers

Next.js recommends using getStaticProps or getServerSideProps instead of getInitialProps to get the best performance from Next.js.

If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.

The reason why Next.js recommends this is that getInitialProps disables Automatic Static Optimization and uses Server-side Rendering.

Using getInitialProps in your _app.js will disable automatic static optimization for all pages in your application. In addition, it will force all your pages to be generated on every request, as they use server-side rendering, which will lead to a bad Time to First Byte (TTFB).

I've made a cheat sheet about Next.js page rendering with live demo and code examples on Github to help understand quickly how it works. This will help you choose the right page rendering strategy with Next.js depending on your use case.

like image 116
Guy Dumais Avatar answered Oct 17 '22 06:10

Guy Dumais