Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

React - Static Site Generation (SSG)

Using static site generation with React

Static Site Generation (SSG) is a technique where HTML pages are generated at build time, allowing for fast and efficient delivery of pre-rendered pages to users. This tutorial covers how to implement static site generation in React using frameworks like Next.js.

Key Points:

  • Static Site Generation (SSG) generates HTML pages at build time.
  • SSG can improve performance and SEO by delivering pre-rendered pages.
  • Next.js is a popular React framework that supports SSG out of the box.

Setting Up Next.js

Next.js is a React framework that enables static site generation. To get started, you need to create a new Next.js project and set up the necessary configuration.


// Install Next.js
npx create-next-app my-static-site

// Navigate to the project directory
cd my-static-site

// Start the development server
npm run dev
                

Creating Pages

In Next.js, you create pages by adding React components to the pages directory. Each file in this directory corresponds to a route in your application.


// pages/index.js
import React from 'react';

const HomePage = () => {
    return (
        <div>
            <h1>Welcome to My Static Site</h1>
            <p>This page is generated at build time.</p>
        </div>
    );
};

export default HomePage;
                

Generating Static Pages

Next.js uses the getStaticProps function to fetch data at build time and generate static pages. This function runs at build time and provides props to your component.


// pages/blog.js
import React from 'react';

const BlogPage = ({ posts }) => {
    return (
        <div>
            <h1>Blog</h1>
            <ul>
                {posts.map(post => (
                    <li key={post.id}>{post.title}</li>
                ))}
            </ul>
        </div>
    );
};

export async function getStaticProps() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const posts = await res.json();
    return {
        props: {
            posts,
        },
    };
}

export default BlogPage;
                

Generating Static Paths

For dynamic routes, you can use the getStaticPaths function to specify which paths to pre-render at build time. This function returns an array of paths to be generated.


// pages/posts/[id].js
import React from 'react';

const PostPage = ({ post }) => {
    return (
        <div>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
        </div>
    );
};

export async function getStaticPaths() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const posts = await res.json();
    const paths = posts.map(post => ({
        params: { id: post.id.toString() },
    }));
    return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);
    const post = await res.json();
    return {
        props: {
            post,
        },
    };
}

export default PostPage;
                

Building and Exporting

After setting up your pages and data fetching functions, you can build and export your static site using the following commands:


// Build the site
npm run build

// Export the static site
npm run export
                

Deploying the Static Site

You can deploy the generated static site to any static hosting service, such as Vercel, Netlify, or GitHub Pages. Follow the hosting provider's instructions for deployment.

Best Practices

Here are some best practices for using static site generation with React:

  • Use static site generation for content-heavy pages that do not change frequently.
  • Leverage Next.js features like getStaticProps and getStaticPaths for efficient data fetching and path generation.
  • Optimize images and assets to improve the performance of your static site.
  • Use incremental static regeneration to update static pages after the initial build.

Summary

In this tutorial, you learned about using static site generation (SSG) with React. SSG generates HTML pages at build time, improving performance and SEO. By setting up a Next.js project, creating pages, fetching data at build time, and deploying your static site, you can take advantage of SSG in your React applications.