Hello, I am guessing you must have heard the buzzword "NEXT JS". Yeah, I thought as much.
In this guide, we are going to focus on what Next js is, the difference between it and React, reasons to use and how to get started.
I hope you are excited, because I am. Let's dive in!
What is Next js?
In a few words, it is simply The React Framework for Production.
Next.js is a flexible React framework that gives you building blocks to create fast web applications.
React on the other hand is a Library, meaning React provides helpful functions to build UI but leaves it up to the developer where the function is to be used.
Developers need to spend time configuring tools and rewriting solutions for common application requirements in React compared to Next.js which handles the tooling and configuration needed for React and provides additional features and optimizations for your application.
FEATURES OF NEXT JS
PAGES
- Pages with Dynamic Routes
Next.js supports pages with dynamic routes. For example, if you create a file called pages/about.js, then it will be accessible at /about.
- Pre-rendering
By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. This results in better performance and SEO.
Next.js has two forms of pre-rendering:
- Static Generation
- Server-side Rendering The difference is in when it generates the HTML for a page._
Static Generation: The HTML is generated at build time and will be reused on each request.
Server-side Rendering: The HTML is generated on each request.
If you can pre-render the page ahead of the user's request, then use Static Generation.
Data fetching in Next.js allows you to render your content in different way :
getStaticPaths
Next.js will statically pre-render all the paths specified by getStaticPaths. You should use getStaticPaths if youβre statically pre-rendering pages.
getStaticProps
If you export a function called getStaticProps (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.
getServerSideProps
You should use getServerSideProps only if you need to render a page whose data must be fetched at the request time.
Client-side data fetching
Client-side data fetching is useful when the content of your pages needs to update frequently. Unlike the server-side rendering APIs, you can use client-side data fetching at the component level.
BUILT-IN CSS SUPPORT
Adding Component-Level CSS
Next.js supports CSS Modules using the [name].module.css file naming convention.
CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same CSS class name in different files without worrying about collisions.
Adding a Global Stylesheet
To add a stylesheet to your application, import the CSS file within pages/_app.js. These styles (styles.css) will apply to all pages and components in your application.
Sass Support
Next.js allows you to import Sass using both the .scss and .sass extensions. You can use component-level Sass via CSS Modules and the .module.scss or .module.sass extension.
Before you can use Next.js' built-in Sass support, be sure to install sass
CSS-in-JS
Examples
It's possible to use any existing CSS-in-JS. The inline style is the simplest:
function Hi() {
return <p style={{ color: 'red' }}>hi there</p>
}
export default Hi;
LAYOUTS
The React model allows us to construct a page from a series of components. Many of these components are often reused between pages. For example, you might have the same footer on every page.
If you only have one layout for your entire application, you can create a Custom Layout and wrap your application with the layout. Since the component is re-used when changing pages, its component state will be preserved
// components/layout.js
import Navbar from './navbar'
import Footer from './footer'
export default function Layout({ children }) {
return (
<>
<Navbar />
<main>{children}</main>
<Footer />
</>
)
}
import Layout from '../components/layout'
export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
IMAGE COMPONENT AND IMAGE OPTIMIZATION
The Next.js Image component, next/image, is an extension of the HTML element. It has built-in performance optimizations to help you achieve good Core Web Vitals which affect google ranking.
To add an image to your application, import the next/image component:
import Image from 'next/image'
Image Sizing
One of the ways that images most commonly hurt performance is when the image pushes other elements around on the page as it loads in. This performance problem has its own Core Web Vital, called Cumulative Layout Shift.
The way to avoid this issue is to always size your images. This allows the browser to reserve precisely enough space for the image before it loads.
next/image is designed to avoid Layout shift and must be sized in one of three ways:
- Automatically, using a static import
- Explicitly, by including a width and height property
- Implicitly, by using layout="fill" which causes the image to expand to fill its parent element.
FONT OPTIMIZATION
Since version 10.2, Next.js has built-in web font optimization.
By default, Next.js will automatically inline font CSS at build time, reducing the time taken to fetch font declarations.
Usage
To add a web font to your Next.js application, add the font to a Custom Document.
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document'
function MyDocument Document {
return (
<Html>
<Head>
<link
href="https://fonts.googleapis.com/css2 family=Inter&display=optional" rel="stylesheet"/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
export default MyDocument
STATIC FILE SERVING
Next.js serves static files, like images, under a folder called public in the root directory. Files inside public can then be referenced.
For example, if you add an image to public/image.png, the following code will access the image:
import Image from 'next/image'
function Avatar() {
return <Image src="/me.png" alt="img" width="64" height="64" />
}
export default Avatar
FAST REFRESH
Fast Refresh is a Next.js feature that gives you instantaneous feedback on edits made to your React components. It is enabled by default in all Next.js applications on 9.4 or newer.
With Next.js Fast Refresh enabled, most edits should be visible within a second, without losing component state.
If you edit a file that only exports React component(s), Fast Refresh will update the code only for that file and re-render your component.
If you edit a file with exports that aren't React components, Fast Refresh will re-run both that file and the other files importing it. So if both Button.js and Card.js import Nav.js, editing Nav.js will update both components.
Finally, if you edit a file that's imported by files outside of the React tree, Fast Refresh will fall back to doing a full reload.
TYPESCRIPT
Next.js provides an integrated TypeScript experience, including zero-configuration setup and built-in types for Pages, APIs, and more.
You can create a TypeScript project with create-next-app using the --ts, --typescript flag like so:
npx create-next-app@latest --ts
# or
yarn create next-app --typescript
# or
pnpm create next-app --ts
ENVIRONMENT VARIABLES
Next.js comes with built-in support for environment variables from Next.js versions 9.4 and up, which allows you to do the following:
Loading Environment Variables
Next.js has built-in support for loading environment variables from .env.local into process.env.
An example .env.local:
DB_URL=localhost
DB_USER=myuser
// pages/index.js
export async function getStaticProps() {
const db = await myDB.connect({
host: process.env.DB_URL,
username: process.env.DB_USER
})
}
ROUTING
Next.js has a file-system based router built on the concept of pages.
When a file is added to the pages directory, it's automatically available as a route.
The files inside the pages directory can be used to define the most common patterns.
Index routes
The router will automatically route files named index to the root of the directory.
pages/index.js β /
pages/blog/index.js β /blog
Nested routes
The router supports nested files. If you create a nested folder structure, files will automatically be routed in the same way still.
pages/blog/first-post.js β /blog/first-post
Linking between pages
The Next.js router allows you to do client-side route transitions between pages, similar to a single-page application.
A React component called Link is provided to do this client-side route transition.
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
</ul>
)
}
export default Home
next/link can cover most of your routing needs, but you can also do client-side navigations without it by using next/router.
The following example shows how to do basic page navigations with useRouter:
import { useRouter } from 'next/router'
export default function ReadMore() {
const router = useRouter()
return (
<button onClick={() => router.push('/about')}>
Click here to read more
</button>
)
}
API ROUTES
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page.
For example, the following API route pages/api/user.js returns a json response with a status code of 200:
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
NEXT.JS ADVANTAGES
React and Next.js both provide great developer experiences in their own way. But why use Next.js and not other frameworks for React? It depends on the production requirements and medium/long-term goals. Below are some advantages.
Speed
Fast rendering
Built-in CSS support
Better image optimization
SEO
ESLint compatible
Easy customization and deployment
API support
RESOURCES TO HELP YOU GET STARTED
Official Docs
Build a website with Next js
Next js crash course
Top comments (0)