Quickstart
Quickstart
npm init next-app nextjs-blog --example "https://github.com/zeit/next-learn-starter/tree/master/learn-starter"
Navigation
- In Next.js, a page is a React Component exported from a file in the pages directory.
- Pages are associated with a route based on their file name. For example, in development:
- pages/index.js is associated with the / route.
- pages/posts/first-post.js is associated with the /posts/first-post route.
- Next.js does code splitting automatically
- in a production build of Next.js, whenever Link components appear in the browser’s viewport, Next.js automatically prefetches the code for the linked page in the background
Link Component
-
use link instead of
a
-
server side
import Link from 'next/link'
Read <Link href="/posts/first-post"><a>this page!</a></Link>
- client side
- The Link component enables client-side navigation between two pages in the same Next.js app.
Assets, Metadata, and CSS
link: https://nextjs.org/learn/basics/assets-metadata-css
Pre-rendering and Data Fetching
-
By default, Next.js pre-renders every page.
-
Next.js has two forms of pre-rendering:
- Static Generation
- Server-side Rendering
- 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.
-
In development mode
- every page is pre-rendered on each request — even for pages that use Static Generation.
-
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.
-
Choosing
- Static if possible
- On the other hand, Static Generation is not a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.
-
static rendering with data
export default function Home(props) { ... }
export async function getStaticProps() {
// Get external data from the file system, API, DB, etc.
const data = ...
// The value of the `props` key will be
// passed to the `Home` component
return {
props: ...
}
}
Dynamic Routes
src: https://nextjs.org/learn/basics/dynamic-routes/implement-getstaticprops
- generate routes based on static content