To read more articles, visit my blog
What is Next.js?
Next.js is a framework for React. It makes developing with React much cleaner and more efficient. In their documentation they define Next.js as: “the React Framework for Production”
And its features truly justified the claim. We will talk about them later.
Why Next.js?
Next.js gives you the best developer experience with all the features you need for production. Both hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No configuration needed.
One bad (or good?) thing about React is that it is highly un-opinionated. It doesn’t force the developer to use some specific library for specific tasks.
But this comes with some cost. Most of the time you have to reach out to an external library or community support for even the most common features like routing, optimization etc.
But that’s not the case in Next.js. It has many features that are built in. You can just start using it immediately. Also, it has support for SSR (server side rendering) which is necessary for SEO optimization. So if you are building something like e-commerce where you care about SEO, then Next.js can be a good option for you.
Okay I hear you. Show me the code!
You can scaffold a Next.js application similarly like React. Open your terminal and type the following command
npx create-next-app name-of-your-app
To run the dev server
cd name-of-your-app
yarn dev
Go to http://localhost:3000 and you will be greeted with the landing page of your awesome application. It’s that simple.
What’s next?
Next.js has awesome documentation (some of the best I’ve ever seen). You can (and should) learn all the basic things from there. But if you want to stick around I will explain some basic concepts here. Let’s start
Declarative Routing
Next.js follows declarative routing. There is a folder named pages inside your project directory (you should not mess with it). Inside that component you can create a new component named home.js
import React from 'react';
export default function Home() {
return <div>Home Page</div>
}
Now if you go to your browser and browse http://localhost:3000/home you can see the home page.
That’s super easy. No need to install react-router or any other library. No need to import the page to any other page. Just create the file and it’s on your browser.
If you need complex routing structure you can create another page like home/details.js and your new page will be available under http://localhost:3000/home
If you need dynamic routing you can add a new page like user/[id].js and if you go to http://localhost:3000/user/1 or http://localhost:3000/user/2 you will see your new page.
Navigation
You don’t need to install react-router or any other navigation library. Next.js provides you with a component named Link
You can use that to navigate between pages.
- If you want to navigate to a route named /
about
you can declare that from your home page like this.
import React from 'react';
import Link from "next/link";
export default function Home() {
return <div>
<Link href={'about'}>Go to About Page</Link>
</div>
}
- The href attribute will determine the route you want to go.
Static Asset
You can put your static assets like images inside the top level public directory. For example put an image named user.png inside public folder and you can serve the image like
<img src="/user.png" alt="user image" className="user-image" />
Styling
Create a new component named
layout.jsx
under a new top levelcomponent
folder.Create a style file named
layout.module.css
somewhere (I am doing it in the same folder).Remember one thing, style files name must have .module.css as a suffix.
Now import the file into your
Layout
component. And use the style as a className property.
import React from 'react';
import styles from './layout.module.css'
export default function Layout({children}) {
return <div className={styles.container}>{children}</div>
}
One great thing about it is that Next.js will automatically create a class property with the format layout_container_random
. The random suffix helps to avoid className collision. How great is that?
If you want to do your styling using sass *then *Next.js also supports that out of the box. But don’t forget to install the dependency first.
npm install sass
After installation you can start using .scss or .sass files directly.
Concept of Global State
Usually we have an App.js
file in our React projects. That Component works as a container for all of our children components. But in Next.js we don’t have a component like that.
Notice one thing. We didn’t import our pages into any other component. So there is no component that can be considered a global child holder. But there is a file named _app.js
. This acts as a mother component. It performs the actions of a App.js
component.
It can apply all styles and can handle global variables between pages. So if we want to apply global styling or some common state between all the pages then _app.js is the place to do that.
Pre Rendering
Pre rendering is a very important concept in Next.js. By default, Next.js pre-renders every page. That means the required HTML files are built in advance, contrary to React where JavaScript code is responsible to build the HTML
There are two types of prerendering
Static Site Generation (SSG)
Service Side Rendering (SSR)
Let’s talk about each of them in brief and try to understand their use cases.
Static Site Generation
If your website has some static content which is unlikely to change very often (like your portfolio) then you don’t have to worry about anything. Next.js will automatically do the SSG for you. Because it already knows what to render. So it generates the required HTML ahead of time resulting in a super fast experience.
But in any serious web application, we depend on some dynamic content that comes from some external API source (your backend server). So how on earth Next.js will pre-render a page that depends on some external api data?
The way to do that is a function provided by NestJS named getStaticProps
.
This is an async function that you can return from your page. It will deliver the result of some api call ahead of time and pass the result as props to your page component.
So Next.js will resolve the necessary props from inside this function ahead of time and pre-render your page. One important thing to note, You can only return this function from inside your page type component. You can’t define it inside any other component.
Use Case for SSG
You can only use getStaticProps
when you already know the result of the api ahead of time. Here we are using JsonPlaceHolder api to fetch a list of blog posts. In your home page, you already know the api that you are going to call to fetch all your posts. It will not depend on some route parameter that will change on every request. So you can use getStaticProps
it in a scenario like this.
import React from 'react';
export default function Home({allPostsData}) {
return <div>
{allPostsData.map(post => <div style={{margin:"20px"}}> {post.title}</div>)}
</div>
}
export async function getStaticProps() {
const jsonResponse = await fetch('https://jsonplaceholder.typicode.com/posts')
const actualPostList = await jsonResponse.json()
return {
props: {
allPostsData : actualPostList
}
}
}
But what will happen if you have a route where you show the details of a blog post with a specific id with a route like blogs/[id]
? How will Next.js know which id is going to be passed and render the page ahead of time?
Unfortunately, you can’t use SSG in this scenario. We have to use server-side rendering (SSR).
Server Side Rendering
We will continue our discussion from the previous example. We need to get the specific blog details by the id and show it on our blogs/[id]
page. We will use another function named getServerSideProps
here.
This function has an extra parameter named context that can be used to get additional information about the requested route. So we can get the blog id from that requested route and get the blog details and pass it as a prop into the details page.
import React from 'react';
export default function BlogDetails({singlePost}) {
return <div>
<div> { singlePost.title}</div>
<div> { singlePost.body}</div>
</div>
}
export async function getServerSideProps(context) {
const jsonResponse = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.query.id}`)
const actualBlogDetails = await jsonResponse.json()
return {
props: {
singlePost : actualBlogDetails
}
}
}
So what’s happening here?
First our
getServerSideProps
the function is getting the id that was requested by our route. For example, if the requested route is http://localhost:3000/blogs/2 then the blog id is 2.It then gets the details for this specific blog.
Pass the data as props into our component.
Our page then renders with the server-generated HTML.
So that’s all the basic concepts that you need to know to start working with Next.js. You can seriously consider your next project to be built with this. It’s really a breeze to work with.
If you already know React then Next.js can be another great addition to your tool belt.
Thank you for making it this far. Happy Coding!
Get in touch with me via LinkedIn or my Personal Website.
Top comments (0)