DEV Community

sandeshsapkota
sandeshsapkota

Posted on

Next JS : Basic features

Image description

Over the years, Next JS is becoming so popular and we have heard many times that our fellow developer talking about it and saying how great it is.

Truly such an amazing framework it is.

Today, I would like to talk about what really Next JS is and will be covering its major features.

What is Next JS

Next JS is a javascript framework built on top of React JS which enables static page generation and server side rendering on traditional react application,

Next JS offers few many other amazing features like such as routing and css modules.

Next JS gives us choice to choose weather to render on client side or to render on server and also we can choose it to be a hybrid application.

Let's go through each of its features.

Static Generation

Static Generation is the method of pre-rendering where the HTML pages gets generated statically at the build time. This means at the end when we build our application for the production, the HTML pages get generated with all the content and data. and Next JS by default do this and we need not to worry about any configuration.

Even if the page use external data which is in api, at the time of building the html will be generated after that api call is resolved.

Here is a small snippet that shows api call inside next js getStaticProps function which sends data to the products component.

export async function getStaticProps() {  
    let products = await fetch('http://localhost:3000/api/products')  
    products = await products.json()  
    return {  
        props: {  
            products: products,  
  }  
    }  
}

function products(props) {  
    const {products} = props  
    return (  
        <div className={'grid gap-4 p-6'}>  
  {  
                products.map((product, index) => {  
                    return <Link key={index} href={{  
                        pathname: '/products/[slug]',  
  query: {slug: product.slug,}  
                    }}><a className={'text-blue-600'}>{product.title}</a></Link>  
  })  
            }  
        </div>  
  )  
}
Enter fullscreen mode Exit fullscreen mode

This is one of the most vital feature of Next JS. This helps to boost performance* and as well as better SEO because the HTML get fetched from the server.

It is recommended to use static generation for static pages like e-commerce pages, blogs and marketing pages.

From the next JS official doc

Static Generation (Recommended): The HTML is generated at build time and will be reused on each request.

*because unlike plain react app where the DOM elements loads after loading the main Javascript file which takes more time.

Server Side Rendering

So we use Static Generation whenever when we have static type pages but what do we do when we have data that keep changing. Here, comes server side rendering.

In server side rendering the HTML get generated at server at each request. for eg we have a products page where products get added and deleted fast at that time we use Next JS getServerSideProps method and fetch api inside this function .

So each time user visit the products page the api get called and html get generated at the server and sends to the client. The way we send props to the component is same with getStaticProps function.

export async function getServerSideProps() {  
    let products = await fetch(apiURL)  
    products = await products.json()  
    return {  
        props: {  
            products: products,  
  }  
    }  
}
Enter fullscreen mode Exit fullscreen mode

CSS Module

Yaaaaay! best part !! with CSS Module we can scope css. Here is how to use CSS Module

First create a css file with Filename.module.css and import it in JS file

.container {  
  padding: 0 2rem;  
}

.title,  
.description {  
  text-align: center;  
}  

.description {  
  margin: 4rem 0;  
  line-height: 1.5;  
  font-size: 1.5rem;  
}
Enter fullscreen mode Exit fullscreen mode
import styles from '../styles/Home.module.css'  

export default function Home() {  
    return (  
        <div className={styles.container}>  
             <div className="grid gap-4">  
                 <h1 className={styles.title}>Next JS Title</h1>  
                 <p className={styles.description}>Next JS Title</p>  
             </div>
        </div> 
     )  
}
Enter fullscreen mode Exit fullscreen mode

So this way the Home.module.css file will get loaded only when the Home component renders. and for the global stylesheet Next JS let us import the css file directly only in app.js file but we can not directly import css files in other js files.

import '../styles/globals.css'
Enter fullscreen mode Exit fullscreen mode

We can also use sass by installing sass package.

Dynamic Routing

Routing with Next JS is super easy. It has file based system routing for pages. for e.g if we add a file product.js inside pages directory and /product will be automatically available as route.

But to be available as route product.js should at least export a string.

function Product() {
  return <h2>Products listing page</div>
}

export default Product
Enter fullscreen mode Exit fullscreen mode

We can also make a product directory and inside it create index.js file and the /product routing will be available.

Automatic Code Splitting

As I have already explained, with css module the specific module css will render only for that component. Like this, Next JS also make chunks of Javascript file for specific files. for e.g if I have a library imported for a page that animates something or does something and is only in the current page, Next JS bundles this library only for this page but if the library used in multiple pages Next JS will bundle it globally.

Image Optimization

If we have heavier images in size, Next JS optimize the correctly sized image for each device, eventually which helps us to improve largest contentful paint. And these images are loaded only when the images entered the viewport.

For this we need to import 'next/image' component

import Image from 'next/image'
function Hero() {
  return (
    <>
      <h1>HERO SECTION</h1>
      <Image
        src={'path to the image'}
        width="350px"  
        height="300px"**
        alt="Picture of the author"
      />
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

The src, width and height properties are necessary for the image component.

When the next image component loads that image sits on already allocated space which means image component solves another web vital Cumulative layout shift. Read more here.

Experience with Next JS

Developing performatic application is such a complex task . pondering over optimizing images , separating css and loading necessary css only for that specific page (scoping) and dealing with initial loading time takes a lot of work and time and Here we have Next JS which solves those problems altogether.

It has been really great experience working with Next JS and I personally feel that it is evolving for the modern web will be there for few years to come.

Thank you for reading.

Top comments (0)