preface

Next.js has been around for a long time, but I haven’t had a chance to look at the framework.

I used to use create-react-app to create react projects, but CRA was very difficult to use. Today, I spent some time checking the official website of Next.

Next.js

While iT is often referred to as an SSR framework, there are many other features that next.js provides, such as these listed on the website:

So, Next. Js is more like a framework, including routing, optimization, SSR, etc.

start

Like create-react-app, Next. Js has a create-next-app scaffolding.

create-next-app demo
Copy the code

Use the above command to create a React project for the Next. Js framework.

routing

Next. Js also provides a routing system that uses name conventions for routing

  • pages/index.jsThe corresponding/
  • pages/xxx/first.jsThe corresponding/xxx/first

Use the Link component for route hops

function FirstPost() {
  return (
    <>
      <h1>First Post</h1>
      <h2>
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </>)}Copy the code

Sometimes you need to jump to the outer chain, just use the tag.

Static resource

The most common use of static resources is images. Next. Js provides the Image component instead of img.

The benefit of the Image component is that it improves the performance of loading images on a web page, automatically loading them on demand and reloading them when they enter the view.

In addition to relative path import, you can also place images under public/images/ and import them using “absolute path”.

export default function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src="/profile.jpg"
        alt="Picture of the author"
        width={500}
        height={500}
      />
      <p>Welcome to my homepage!</p>
    </>)}Copy the code

MetaData

The Meta Data of a web page mainly refers to the contents of the element. Next. Js directly provides a component to wrap Meta Data.

<Head>
   <title>First Post</title>
</Head>
Copy the code

The advantage is that you can write different Meta Data in different page components.

CSS

The styles section is similar to create-react-app. Use the CSS module and name it xxx.module. CSS, otherwise all other CSS files need to import ‘xxx. CSS ‘to introduce CSS styles.

It is important to note that global styles can only be introduced inpages/_app.jsTo the root file of.

The preceding operations are the same for Sass.

pre-rendered

Finally, it’s time for the pre-render that Next. Js is most proud of. Next. Js provides three rendering methods:

  • Client-side Rendering (CSR)
  • Static Generation (SSG)
  • Server-side Rendering (SSR)

Client-side Rendering

Client-side rendering is actually the scene we often see before and after the separation: just provide an HTML, get

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

This method of rendering has the following disadvantages:

  • SEO is not friendly
  • The blank screen lasts for a long time

Smart front-end programmers think, When I visit the URL, I directly put the data into THE HTML, then the crawler can directly get the information of the page, to solve the problem of SEO. Similarly, there is no need to wait for JS loading to send Ajax to get data, and the basic data will be displayed first, which can solve the problem of long white screen time.

So, pre-rendering is SSG and SSR.

Static Generation

Static Generation writes data directly to HTML when building time production, so generally these data are Static and fixed.

export async function getStaticProps() {
  const allPostsData = getSortedPostsData()
  return {
    props: {
      allPostsData
    }
  }
}
Copy the code

Export the getStaticProps function, which contains the logic to get the data at build time.

Server-side Rendering

In general, we rarely use static data, and generally use dynamic data. It is not possible to package the data again every time it is updated. So there’s Server-side Rendring.

Server-side Rendering performs a data capture and generates HTML to return to the front end each time the URL is requested.

Looking at this, you may be thinking: How is Next. Js different from PHP and JSP before? They all spit HTML. In Next. Js, SSR is actually isomorphic rendering, that is, a set of code is executed at both ends. Please refer to this answer for specific differences

Just like Static Generation, server-side Rendering has a corresponding need to export a getServerSideProps function.

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

Dynamic routing

Dynamic routing is a route that generates posts/: ID, which can be the ID of a post. You can name the file as [id].js.

In the page component file, you can get params using the getStaticProps and getServerSideProps mentioned earlier:

export async function getStaticProps({ params }) {
  const postData = getPostData(params.id)
  return {
    props: {
      postData
    }
  }
}
Copy the code

Pages /posts/[…id].js matches /posts/a/b route and /posts/a,… Is full match.

API

In addition to normal page writing, sometimes we need to provide an API interface, you can add a file under Pages/API, the file name is the API name.

Note: You cannot add fetch data to getStaticProps and getStaticPaths because they only run on the Server side, not the client side. Instead, use the Helper function to fetch data.

The API code will not be in the client side bundle.

The deployment of

Deploying this section of next.js recommends using Vercel for deployment.

Because Vercel itself serves Next. Js, all you need to do is connect to the Github Repo and deploy with one click.

conclusion

To summarize, Next. Js provides the following functionality:

  • LinkComponent for easy routing
  • ImageComponent to optimize picture loading
  • File path generation routing mechanism, dynamic routing use[id].jsSuch an order
  • Isomorphic development mode of SSR and SSG (in fact, export a function corresponding to the name, just get the data in advance)
  • Style aspect andcreate-react-appalmost