Back to Blog
Introduction to Next.js: The React Framework
Next.jsReactJavaScriptSSR

Introduction to Next.js: The React Framework

2023-08-10Jahin Utsho

Introduction to Next.js: The React Framework



Next.js is a React framework that enables functionality such as server-side rendering, static site generation, and API routes. It's designed to make building production-ready React applications simpler and more efficient.

Why Next.js?



  • Server-side Rendering (SSR): Improves performance and SEO
  • Static Site Generation (SSG): Pre-renders pages at build time for even better performance
  • API Routes: Build API endpoints as part of your Next.js application
  • File-based Routing: Create routes based on your file structure
  • Built-in CSS and Sass Support: Import CSS/Sass files directly in your components

    Getting Started



    Create a new Next.js app using create-next-app:

    bash
  • npx create-next-app my-next-app cd my-next-app npm run dev

    Pages and Routing



    Next.js uses a file-system based router. Files in the pages directory automatically become routes:

    jsx
    // pages/index.js 
  • accessible at /
  • export default function Home() { return

    Home Page

    }

    // pages/about.js
  • accessible at /about
  • export default function About() { return

    About Page

    }

    // pages/posts/[id].js
  • accessible at /posts/1, /posts/2, etc.
  • import { useRouter } from 'next/router'

    export default function Post() { const router = useRouter() const { id } = router.query

    return

    Post: {id}

    }


    Data Fetching



    Next.js provides several ways to fetch data for your pages:

    getStaticProps (Static Site Generation)



    jsx
    export default function Blog({ posts }) {
      return (
        
      {posts.map((post) => (
    • {post.title}
    • ))}
    ) }

    // This function runs at build time export async function getStaticProps() { const res = await fetch('https://api.example.com/posts') const posts = await res.json()

    return { props: { posts, }, } }


    getServerSideProps (Server-side Rendering)



    jsx
    export default function Page({ data }) {
      return 
    Data: {data}
    }

    // This function runs on every request export async function getServerSideProps() { const res = await fetch('https://api.example.com/data') const data = await res.json()

    return { props: { data } } }


    API Routes



    Create API endpoints by adding files to the pages/api directory:

    jsx
    // pages/api/hello.js
    export default function handler(req, res) {
      res.status(200).json({ name: 'John Doe' })
    }
    


    Conclusion



    Next.js simplifies many aspects of building React applications, from routing to data fetching to deployment. Its hybrid approach allows developers to choose the right rendering strategy for each page, making it a powerful tool for modern web development.

    Related Posts