Why NextJS?
Tags: webdev, javascript, nextjs, react
Published: 2023-07-11 15:58:05



## WHY USE NEXT.JS FOR YOUR PROJECT?

**INTRODUCTION**
Web development has evolved so much over the years, we are now able to do so much while writing much less code and even, with less stress. There is a shiny new framework that comes out every month (just kidding, not every month ) and we have to keep up with all of them. Top of the list of these frameworks we have to learn is Next.JS, which is a framework for the web, built on React. It provides a whole lot of out of the box features and provides more tooling that makes our application perform better. We are going to be looking at the advantages of using Next.JS for building our web applications.

**Server Side Rendering**
Server Side Rendering also called SSR or Dynamic Rendering, enables your page to render user data on the server side and not the client side, this makes it to load fast, as it’s server side generated. This method of displaying data makes your web application load faster, reduces the amount of JavaScript that needs to be downloaded for your page to load. You can use SSR if your page needs to render data that changes with time. SSR can also help improve the SEO of your website. This is because your pages are rendered on the server side and search engines will be able to index your pages faster and easily. This kind of data is referred to as dynamic data. The main difference between static site generation(SSG) and server side generation(SSR) is that, with SSG, your page renders at build time while with SSR, your pages data render on request. The only time you should use SSR is when you want to render dynamic data which must be shown at request time. To render server side data, you use the “getServerSideProps” key word to fetch such data and pass it down to another component. Take a look at the code snippet below:

```

export const getServerSideProps = async () => {
  const res = await fetch('https://api.com)
  const data = await res.json()
  return { props: { data } }
}

```
The data will then be passed as props to the component below:

```

export default function Page({ data }) {
  return data
}

```
Another way of rendering data is using the Static Side Generation(SSG).

**Static Side Generation**
This is another way of rendering data on our web application. A web  page that uses SSG is a web page that generates its HTML at build time. You can, however, generate pages on your web application without an external data, take for example, the code snippet below:

```

export default function Data() {
  return <div>Data</div>
}

```
This doesn’t need any data to be able to display anything on our web application. A HTML page is generated at build time.

**Static Side Generation with data:**

If your page depends on external data, then you can use “getStaticProps” to fetch the data. You might want to pre-render a list of product on your web application, at build time, you can do that using the code snippet below:
First, you’d have to export an async function that gets called at build time, using the keyword, “getStaticProps”, just like this:

```

// This function will be called at build time
export async function getStaticProps() {
  // Get data from an external api
  const res = await fetch('https://.../products)
  const products = await res.json()
 
  // By returning { props: { products} }, the Store component
  // will receive `products` as a prop at build time
  return {
    props: {
      products,
    },
  }
}

```
And this is where the products that were fetched will be rendered:

```

export default function Store({ products}) {
  // Render products...
}

```
Just to reiterate, SSG helps our web applications load faster, because data is rendered at build time. It also reduces loading time as a result of this.

**Incremental Static Regeneration**

This is another powerful way of rendering static data and also updating it, even after building your page. This is more like the best of both worlds; SSG & SSR. To be able to use ISR, you have to add the “revalidate”  prop to the “getStaticProps” keyword. You can choose the number of seconds you want this data to be revalidated. When a request is made to an already built page with data pre-rendered, statically, it will show cached data. According to the Next.js documentation, “Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous.” It also said that “After the 10-second window, the next request will still show the cached (stale) page”. This regeneration is triggered automatically by Next.JS in the background. Once the generation of a new page works fine, Next.JS will invalidate the old data and show you an updated one. If this fails, the old data will show and remain unaltered. Take a look at the code snippet below to be able to use ISR:

```

// This function will be called at build time on the server-side.
// It could be called again if;
// revalidation is enabled and a new request comes in
export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()
 
  return {
    props: {
      posts,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request is made
    // - At most once every 10 seconds because revalidation is set to 10 seconds.
    revalidate: 10, // In seconds
  }
}
```

The “posts” having been passed down as props is also received in the blog component below:

```

function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}
export default Blog
```
 Lastly, using ISR can help boost SEO, faster loading time and also, flexible updates on your page, without having to rebuild your entire website from scratch.

**Routing**
This is one very powerful feature of Next.JS. It comes with a file based routing system, out of the box. Normally with React, we’d have to set up a Router after installing React-router-dom. With every version released, setting up React-router-dom became weirder and more difficult to understand, especially for newbies. Next.JS solves that problem by simply making the Routes in our Next.JS application pages based. Next.JS defined it as a “file-system based router built on concepts of pages.” That means, once you create a new file in the pages directory, it automatically becomes a new Route. All you have to do is to open up your application on your localhost and open up the new route created. You could create a folder named About and a file in it named page.js. The new route will be /about. It’s as simple as that. You could also nest folders into another, creating different routes. You could have pages/dashboard/contact/page.js and this would route to /dashboard/contact, contact being the destination page. Lastly, we can create dynamic routes very easily this way: pages/posts/[id].js and this will be accessible at posts/1 or posts/2 or posts/3, it’s that easy! Click [this](https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes ) to learn more about dynamic routing.

**Image Optimization**
Images account for a very huge portion of a website’s weight and could slow down our web application, sometimes. Next.JS out of the box helps us to optimize images which then helps our web applications load much faster. Next.JS extends the HTML “img“ tag and therefore helps images added on websites lightweight, without having to compromise on quality of images. According to the Next.Js documentation, “Images are only loaded when they enter the viewport using native browser lazy loading, with optional blur-up placeholders”. To be able to add an image to your Next.JS application, you have to first, import Image at the top level, in your code, just like you can see below:

```
import Image from 'next/image'

```

After that, you can define the source (src) of your image. It could either be local or remote. If it’s local, it can be added using the code snippet below:

```
import Image from 'next/image'
import userPic from '../public/me.jpg
 
export default function Page() {
  return (
    <Image
      src={userPic}
      alt="Picture of the user"
      // width={500} automatically provided for local images
      // height={500} automatically provided for local images    />
  )
}
```

However, if it is a remote image, the src will have to be a url string. You’d have to manually provide the width and height, since Next.JS doesn’t have access to this during the build process. Take a look at the code snippet below for example:

```

import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
   src="https://mypicworld.com/my-home/profile.png"
      alt="Picture of my home"
      width={500}
      height={500}
    />
  )
}
```

For the second option, you’d have to go to next.config.js to define a list of supported URLs and you have to be specific as possible with the URLs. This will help you avoid any error that will come from using an external URL to display pictures. For example, the configuration below will only allow images from the declared URL:

```

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: mypicworld.com/my-home
        port: '',
        pathname: '/my-home/**',
      },
    ],
  },
}

```

To learn more about Image optimization, click [this](https://nextjs.org/docs/pages/building-your-application/optimizing/images).


In conclusion, before you start using Next.JS, you have to be familiar with JavaScript, this will help you understand Next.JS more because it’s a framework built on React. You also have to know React before moving to Next.JS. I can’t tell how much React and JavaScript you need to know, first, but I’d suggest you get comfortable with the two, building some cool stuff with both of them, before advancing further. To learn JavaScript, you can start [here](https://www.w3schools.com/js/), to learn React, you can start [here](https://react.dev/), also. Goodluck.