WHY I LOVE NEXT.JS

Posted by Mišo Barišić on August 7, 2021 (7m read)

Next.js is React on steroids

Seriously. It offers automatic code splitting, easy API creation, static page generation and much more.

Setup

Next has an extensive list of examples which you can start using by entering a single command:

npx create-next-app // or npx create-next-app -e [example]

File system based routes

Every single file inside the pages/ directory is automatically a separate page.

// pages/index.js export default function Page() { return <h1>This is a simple page!</h1> }

Fetching props

Fetching props should be offloaded to getStaticProps or getServerSideProps, these functions are not bundled with the website, therefore using private API keys is not a sin here.

Static page props

// Pass props to a page at build time export default function StaticPage({data}) { return <h1>{data.heading}</h1> } // getStaticProps gets executed at page build time // *NOT* every time the page is visited export async function getStaticProps() { const data = apiRequest() return { props: { data }, } }

Server side props (Server side generation)

NOTE! These pages are considered as Serverless functions.

// Dynamic page export default function SSGPage({data}) { return <h1>{data.heading}</h1> } // getServerSideProps gets executed on every page visit export async function getServerSideProps() { const data = apiRequest() return { props: { data }, } }

Seamless anchor tag routing

Instead of just using an anchor tag which forces "a page (re)load on click", wrap it inside Next's Link component and navigating around your website will become seamless and more responsive.

export default function DoNot() { return ( <a href="https://www.misobarisic.com"> Home </a> ) }
// import Link from "next/link" export default function Do() { return ( <Link href="https://www.misobarisic.com"> <a>Home</a> </Link> ) }

REST API example

Creating APIs is dead easy. No point in breaking your head with Express, Django, Spring Boot... NOTE! API endpoints are considered as Serverless functions.

// pages/api/example // https://domain.tld/api/example export default function handler(req, res) { res.status(200).json({hello: 123}) }