Usage scenarios

  • You must use a wrapper, such as WebPack, to package your code and a compiler, such as Babel, to transform it.
  • You need to optimize for the production environment, such as code splitting.
  • You may need to pre-render some pages to improve page performance and SEO. You may also want to use server-side or client-side rendering.
  • You may have to write some server-side code to connect the React application to the datastore.

advantage

  • Intuitive, page-based routing system (with dynamic routing support)
  • Pre-rendered. Support for static generation (SSG) and server-side rendering (SSR) at the page level
  • Automatic code splitting, improve page loading speed
  • Client route with optimized prefetch function
  • Built-in CSS and Sass support, and support for any CSS-in-JS library
  • The development environment supports quick refreshes
  • Build API functionality using Serverless Functions and API routing
  • Fully extensible

1. Reduced-form routing

Next. Js automatically generates routes based on the file structure in the Pages directory

In Next. Js, a page is a React component that is exported in the Pages directory.

Pages associates routes based on the file name in its directory, for example:

  • pages/index.jsWith routing /(Root path) association
  • pages/post/first-post.jsWith routing /posts/first-postassociated

Ii. Jump page -Link

In next.js, we use the Link tag to wrap around the A tag to jump to the page

import Link from 'next/link'

Read <Link href="/posts/first-post"><a>this page!</a></Link>
Copy the code

Client-side Navigation

The Link component enables client-side navigation between two pages in the same next.js application.

Client-side navigation means to jump to the page using JavaScript code, which is faster than the default navigation performed by the browser.

The difference between Link and A tags

jumps refresh the entire page, does not

Code splitting and Preloading

Next. Js automatically splits the code so that each page loads only what is needed for that page. This means that when the home page is rendered, the code for the other pages is not initially provided.

This ensures that the home page loads quickly even if you add hundreds of pages.

Code that loads only the page you request also means that the page is quarantined. If a page throws an error, the rest of the application will still work.

Furthermore, in production versions of next.js, whenever the Link component appears in the browser viewport, next.js automatically preloads the code for the page in the background. When you click the link, the code for the target page will already be loading in the background, and the page conversion will be complete soon!

conclusion

Next. Js automatically optimizes your application to achieve the best performance by code splitting, client-side navigation, and preloading.

You can create files directly in the Pages directory (automatically generating routes) and use the built-in Link component. No other routing libraries are required.

Note: Use A if you want to link to an external page outside the Next. Js application

Learn <a href="https://www.nextjs.cn">Next.js! </a>Copy the code

If you need to add attributes such as className, add them to the A tag instead of the Link tag. Here’s an example.

// Example: Adding className with <Link>
import Link from "next/link";

export default function LinkClassnameExample() {
  // To add attributes like className, target, rel, etc.
  // add them to the <a> tag, not to the <Link> tag.
  return (
    <Link href='/'>
            
      <a className='foo' target='_blank' rel='noopener noreferrer'>
        Hello World
      </a>
    </Link>
  );
}
Copy the code

Resources, metadata, and CSS

You can see that in this section

  • How to add static files (eg: Images) to next.js
  • How do I customize the head for each page
  • How to inpages/_app.jsTo add global styles
  • How to use CSS Modules to build reusable React components

3.1 next.js will read static resources directly from the public directory as the root path

For example, a logo.svg image in the public folder can be used like this

<img src='/logo.svg' alt='Vercel Logo' className='logo' />
Copy the code

3.2 Customizing the Document head

Function: you can define different metaData, title, link, and so on for each sub-page of a single page application

<Head>
  <title>6666p</title>
  <link rel='icon' href='/favicon.ico' />
</Head>
Copy the code

3.3 the CSS Styling

Soft.js uses a “CSS-in-JS” library internally called Styled – JSX

It allows you to write CSS in the React component, and CSS styles will be limited (other components will not be affected).

Soft.js has built-in support for styled- JSX, but you can also use other popular CSS-in-JS libraries, such as Styled – Components.

Method 1: CSS-in-JS

<style jsx>{`... `}</style>
Copy the code

Method 2: Write and import the CSS

Next. Js has built-in support for CSS and Sass, and you can import.css and.scss files directly.

In this article, we’ll also discuss how to write and import CSS files in next.js. We’ll also discuss the built-in support for CSS modules and Sass in next.js.

3.4 the Layout Component

Layout.js

Create a components folder in the root path, go to the folder and create layout.js

export default function Layout({ children }) {
  return <div>{children}</div>;
}
Copy the code

Usage:

// /pages directory
import Link from "next/link";
import Head from "next/head";

import Layout from ".. /.. /components/layout";

export default function FirstPost() {
  return (
    <Layout>
      <h1>First Post</h1>
    </Layout>
  );
}
Copy the code

Add CSS

Style the React component using CSS Modules

Important: To use CSS Modules, the CSS file name must end with .module.css.

In the Components directory, create a layout.module. CSS file with the following content

.container {
  max-width: 36rem;
  padding: 0 1rem;
  margin: 3rem auto 6rem;
}
Copy the code

Used in layout.js

import styles from "./layout.module.css";

export default function Layout({ children }) {
  return <div className={styles.container}>{children}</div>;
}
Copy the code

Automatically generate a globally unique className

That’s what the CSS Module does: automatically generate unique class names. As long as you use CSS Modules, you don’t have to worry about class name conflicts.

In addition, the code-splitting functionality of next.js can also be used on CSS modules. It ensures that the minimum amount of CSS is loaded per page. This reduces the size of the packaged code.

CSS modules are extracted from JavaScript bundles at build time and generate.css files that are automatically loaded by next.js.

3.5 Global Styles

CSS Modules are component-level styles, but if you want to load the same CSS on every page, Next.

styles/global.css

html.body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu,
    Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  line-height: 1.6;
  font-size: 18px; {} *box-sizing: border-box;
}

a {
  color: #0070f3;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

img {
  max-width: 100%;
  display: block;
}
Copy the code

pages/_app.js

Create the _app.js file in the pages directory and add the following contents

import ".. /styles/global.css";

export default function App({ Component, pageProps }) {
  return <Component {. pageProps} / >;
}
Copy the code

4. Pre-rendering and data acquisition

You can see it here

  • Next. Js pre-render
  • There are two ways/forms of pre-rendering: static generation and server-side rendering
  • Static generation is used in two scenarios
    • Need to obtain external data data –getStaticProps
    • No external data needs to be retrieved

4.1 Pre-rendering(Pre-rendering)

Before we talk about data retrieval, let’s talk about one of the most important concepts in next.js: pre-rendering.

By default, Next. Js prerenders every page.

This means that Next. Js generates HTML for each page up front, rather than doing it all in client-side JavaScript.

Pre-rendering can lead to better performance and SEO.

Each generated HTML is associated with the minimum amount of JavaScript code required for that page. When the browser loads the page, its JavaScript code runs and makes the page fully interactive. (This process is called hydration.)

4.1.1 Check whether prerendering is effective

You can check to see if the prerender works by performing the following steps:

  1. Disable JavaScript in your browser (in Chrome) and…
  2. Refresh the current page of the browser to try to access this page.

You should see your application render without JavaScript. If the interface displays complete HTML, the site has pre-rendered the Web application as static HTML, allowing you to view the application interface without running JavaScript.

If your app is a normal React. Js app (without Next. Js), pre-rendering is not done, so if JavaScript is disabled, you will not see the React app’s normal interface. For example: This site is built with plain React. Js

  1. Disable JavaScript and refresh to access the same page.
  2. The screen says “You need JavaScript enabled to run this application.” This is because the application is not prerendered as static HTML.

4.1.2 Summary: Pre-render VS No Pre-render (Single page app – Client Render)

The HTML is pre-rendered before accessing the browser. In the browser side to visit a page, and then through JS binding interactive events!

Rendering HTML and binding interactive events are done through JS when the browser accesses the page

4.1.3 Two ways of pre-rendering

Next. Js has two forms of pre-rendering: Static Generation and server-side Rendering.

The difference between the two approaches is the timing of the HTML page generation for the page.

  • Static generation (recommended) : HTML is generated at build time and reused on every page request.
  • Server-side rendering: HTML is regenerated on each page request.

In a development environment (when you do NPM run dev or YARN Dev), each page is pre-rendered on the server side – despite setting the page to be “statically generated”

Importantly, Next. Js allows you to create new pages for each pagechooseThe way of pre-rendering. You can create a “mixed rendering” next.js application that uses “static generation” for most pages and “server-side rendering” for others.

4.2 Timing of static generation and server rendering

We recommend that you use static generation whenever possible, because all of your pages can be built once and hosted to the CDN, which is much faster than having the server render the page per page request. You can also use “static generation” for many types of pages, including:

  • Marketing page
  • Blog posts
  • List of e-commerce products
  • Help and documentation

Ask yourself: “Can I prerender this page before the user asks?” If the answer is yes, select “Static generation.”

On the other hand, if you can’t pre-render a page before the user requests it, “statically generated” isn’t a good idea. This may be because your page needs to display frequently updated data and the page content changes with each request.

In this case, you can do either of the following:

  • Use “static generation” with client-side rendering: You can skip pre-rendering parts of the page and fill them with client-side JavaScript. For more information about this approach, see the documentation in the Getting Data section.
  • Use server-side rendering: Next-.js to pre-render for each page request. Because the CDN cannot cache the page, it will be slower, but the pre-rendered page will always be up to date. We discuss this approach below.

4.2 Get data statically generated (get data when packaging build)

Static generation may or may not have data.

So far, none of the pages we’ve created need to extract external data. These pages are automatically generated statically when the application is built for the application.

However, for some pages, you may have to get some external data before rendering the HTML. Maybe you need to access the file system, get an external API, or query a database at build time. Next-js supports this right out of the box – static generation with data.

4.2.1 In static generation modegetStaticPropsTo get the data

To retrieve this data during pre-rendering, Next. Js allows you to export an async function called getStaticProps from the same file. (When you export a React component, you can also export an asynchronous function called getStaticProps.)

  • This function is called at build time,
  • And allows you to pre-render the data captured aspropsParameters are passed to the page.
function Blog({ posts }) {
  // Render posts...
}

// This function is called at build time
export async function getStaticProps() {
  // Call the external API to get the list of blog posts
  const res = await fetch("https://... /posts");
  const posts = await res.json();

  // By returning the {props: posts} object, Blog module
  // The 'posts' argument will be received at build time
  return {
    props: {
      posts,
    },
  };
}

export default Blog;
Copy the code

The getStaticProps function tells Next-.js: “Hey, this page has some data dependencies – so when you prerender this page at build time, make sure you request the data first!”

Note: In development mode, getStaticProps runs on each request instead.

4.2.2 Adding interface Request Code

inpages/index.jsAdd the following code
import Link from "next/link";

import Layout from ".. /components/layout";
import { getSortedPostsData } from ".. /lib/posts";

export default function Home({ allPostsData }) {
  return (
    <Layout home>
      <section>
        <ul>
          {allPostsData.map(({ id, title }) => (
            <li key={id}>
              <Link href={` /posts/ ${id} `} >
                <a>{title}</a>
              </Link>
            </li>
          ))}
        </ul>
      </section>
    </Layout>
  );
}

export async function getStaticProps() {
  const allPostsData = getSortedPostsData();
  return {
    props: {
      allPostsData,
    },
  };
}
Copy the code
new lib/posts.jsAdd the following content to the file

In lib/posts.js, we implement getSortedPostsData to get data from other sources (such as external apis)

export async function getSortedPostsData() {
  // Instead of the file system,
  // fetch post data from an external API endpoint
  const res = await fetch("..");
  return res.json();
}
Copy the code

Note: next.js automatically imports fetch() on both the client and server. You don’t need to import it manually.

In addition, you can query the database directly. Because getStaticProps only runs on the server side. It will never run on the client. It won’t even be included in the browser-specific PACKAGED JS code. This means you can write code for things like direct database queries without having to send it to the browser.

4.3 Difference between development environment and production Environment

  • In the development environment (npm run devyarn dev), getStaticPropsThe function is executed each time a request is made
  • In a production environment,getStaticPropsOnly executed when the build is packaged

Since it runs at build time, you won’t be able to use data that is only available at request time, such as URL query parameters or HTTP headers.

4.4 It can only be used on the Page

GetStaticProps can only be exported from the page. You can’t export it from a non-page file. One reason for this limitation is that React needs to have all the necessary data before rendering the page.

4.5 What if I need to get the data on request?

If you cannot pre-render a page before the user requests it, static generation is not recommended. Maybe your page displays frequently updated data and the page content changes with each request. In this case, you can try server-side rendering or skip pre-rendering. 六四屠杀

4.3 Get data as server rendered (get data on each request)

If you want to get the data when the page is requested rather than at build time, you can use ** server rendering **To use server-side rendering, you need to export one in the pagegetServerSideProps

export async function getServerSideProps(context) {
  return {
    props: {
      // props for your component}}; }Copy the code

Because getServerSideProps is executed only on the request, it can take some of the request parameters in its context

The time when getServerSideProps was used

Usage scenario: data must be requested before pre-rendering.

The time to the first byte (TTFB) will be slower than getStaticProps because the server must evaluate the results on each request, and the CDN cannot cache the results without additional configuration.

4.4 Client Rendering

If you don’t need to fetch data before pre-rendering, you can use client-side rendering,

The statically generated (pre-rendered) portion of the page that does not require external data. After the page loads, JavaScript is used to get the external data from the client and populate the rest.

For example, this approach applies to user dashboard pages. Because the information center is a private, user-specific page, SEO is irrelevant, and the page does not need to be rendered up front. Data is updated frequently, which requires that the data be retrieved at the time of request.

4.5 SWR

The team behind next.js created a React Hook called SWR to fetch data. If you want to fetch data on the client side, we strongly recommend that you do so. It handles caching, revalidation, focus tracing, interval recapture, and more. We won’t cover the details here, but here’s an example usage:

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>;
}
Copy the code