Blog>
Snippets

Incremental Static Regeneration with Loading UI Fallback

Example of how to use Incremental Static Regeneration (ISR) in Next.js 14 with a UI fallback during the regeneration process.
import { useRouter } from 'next/router';

export default function Page({ data }) {
  const router = useRouter();

  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {/* Render page content with data */}
      {data && <p>{data.title}</p>}
    </div>
  );
}
This is a functional component in Next.js that checks if the page is currently in 'fallback' mode, which means the page content is being regenerated. If 'router.isFallback' is true, a loading UI is shown. If there is data, it renders the content of the page with that data.
export async function getStaticProps() {
  // Fetch data from an API or local file
  const data = await fetchData();

  return {
    props: { data },
    revalidate: 10 // Set revalidation time (in seconds)
  };
}

async function fetchData() {
  // logic to fetch data
  return { title: 'Hello, World!' };
}
This code snippet defines the 'getStaticProps' function which is used to fetch data that will be passed to the page component as props. It uses 'revalidate' option set to 10, which means every 10 seconds, Next.js may re-run this function to update the static content if there are requests coming in.