Nextjs rendering
unit of work that converts React code into HTML represented on your UI.
with next.js therer are 3 types of rendering: server-side, static site generation, cliend-side
.
Server-side and static site generation are also called pre-rendering
bc the fetching of external data and transformation of React components into HTML happens before the result is sent to the client.
client side rendering
In a standard React app, the browser receives and empty HTML shell from the server along with the js instructions to construct the UI. This is client side rendering. You can do client side rendering by fetching data with React's useEffect
hook or [useSWR](https://swr.vercel.app/)
you could statically generate parts of the page that do not need external data and when the page loads, fetch external data with JS and populate the remaining part.
useSWR()
React hook made by Next team. It handles caching, revalidation, focus tracking, refetching on interval, and more
example:
import useSWR from 'swr';
function Profile() {
const { data, error } = useSWR('/api/user', fetch);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>hello {data.name}!</div>;
}
Pre-rendering in Next.js
In contrast Next.js pre-renders every page by default. in every request it sends the generated HTML, JSON data and JS. on the client, HTML is used to show a fast non-interactive page, while Reacts uses JSON and JS to make components interactive. This is hydration.
Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page.
- Static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request.
- Server-side Rendering is the pre-rendering method that generates the HTML on each request.
Importantly, Next.js lets you choose which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.
server side rendering (SSR) - getServerSideProps
- runs on request time
- To opt to server-side render pages use
getServerSideProps()
context
parameter contains the request specific parameters.- time to first byte will be slower than SSG
apparently I can't call getServerSideProps from within a component. (in my case I am trying to do it from the Sidebar component). It has to be called from a Page. see this thread
data fetching is done differently with the new AppRouter.
export async function getServerSideProps(context) {
return {
props: {
// props for your component
},
};
}
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetServerSideProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return repo.stargazers_count
}
React 18 and Next 12 introduce an alpha version of React server components. Server components that are completely rendered on the sever and do not require client side javascript.
static site generation (SSR) - getStaticProps
- in development, getStaticProps runs on every request, in prod it runs on build time.
- getStaticProps is to enable static site generation.
- can only be exported from page files
You should use getStaticProps if:
The data required to render the page is available at build time ahead of a user’s request
The data comes from a headless CMS
The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance
The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Middleware to rewrite the path.
since code in getStaticProps
only runs on the server and won't ever be sent to the client, you can write queries in them instead of calling an API. this code can be shared by the API and the client using a lib\
directoriy
getInitialProps
is being fazed out
can run both on server as well as client. you can check where it is running by checking for the existence of ctx.req
Incremental Static Regeneration
allows you to create or update static pages after you've guild your site. This enables you to use static-generation on a per-pag basis, without needing to rebuild the entire site.
to use ISR, add the revalidate
prop the getStaticProps
.
With Next.js it lets you choose which rendering method to use on a page-by-page basis.