← Home

next

3 min read

Methods

 

There are four methods in Next.js:

 

getInitialPropsused to do server-side rendering on a page and allows you to do initial data population. It disabled automatic static optimization.

getStaticPropsused to fetch or inject data into a react component at compile time.

getServerSidePropsused to fetch or inject data into a react component at request time.

getStaticPathsgenerates a list of paths, statically generated for dynamic routes, if a page uses getStaticProps.

 

Routing

RoutingNext.js, compared to create-react-app for example, supports a file-system based route. Pages at the level of /pages folder are static and several other layers may be added, but a great thing about Next.js is that it also allows to manage nested routes dynamically, based on available data

 

Linkslinks in next.js are being rendered inside the <Link href=`https://github.com/` target=`_blank` rel=`noopener noreferrer`/> component imported from next/link.

 

[slug].jsIf we want to display a list of authors, we might want to create a route that looks like /authors/book/${id} . That means in the /authors folder we add a file named [slug].js where the current book is being fetched.

 

[...slug].jsWhen you want to add deep routing that is /authors/id/books the brackets are being used alongside the spread operator.

 

[[...slug]].jsIn addition to the above mentioned ways to create routes, there is [[...slug]].js which tells Next.js that some routes won't require a parameter.

 

Rendering

Automatic static optimizationif a page has no blocking data requirements, next.js automatically determines that a page is static (it can be prerendered). This is done in the absence of getServerSideProps and getInitialProps in the page. Automatic static optimization allows creation of hybrid applications with both server-rendered and statically generated pages.

 

Pre-renderingInstead of generating HTML by client-side JavaScript, Next.js generates it for each page in advance on the server side. This can improve SEO and allows for the application to work without JavaScript. Server-Side Rendering(generates the HTML on each request) and Static Site Generation(generates the HTML at build time) are also referred to as Pre-Rendering because the fetching of external data and transformation of React components into HTML happens before the result is sent to the client.

 

HydrationHTML is used to show initially a fast non-interactive page on the client, while React uses the JSON data and JavaScript instructions to make components interactive, like attaching event handlers to elements.

 

Compilingis transforming code into something parsable by browsers.

 

Bundlingis resolving your applications dependency graph and reducing the number of files.

 

Elements

<Head /> The <Head /> component should only be used for any <head> code that is common for all pages. For all other cases, such as <title> tags, use next/head in your pages or components.