Static Generation using getStaticProps
Static Generation is a Next.js feature that generates HTML pages at build time. This means that the content of these pages is pre-rendered and served as static files, making them extremely fast to load. Static Generation is suitable for pages with content that doesn’t change frequently, such as marketing pages, blogs, or product listings.
How it Works:
- When you use getStaticProps in a Next.js page, Next.js will pre-render that page at build time.
- During the build process, Next.js calls getStaticProps, fetches data, and generates the HTML for the page with that data.
- The generated HTML is then served to the client, making subsequent visits to the page very fast as the content is already there.
Use Cases:
- Content that doesn’t change often (e.g., blog posts, product descriptions).
- SEO-friendly pages as search engines can crawl and index the static content easily.
- Improving initial load times for users.
Syntax:
export async function getStaticProps() {
// Fetch data from an API or database
const data = await fetchData();
return {
props: {
data,
},
};
}
Example: Below is an example of Fetching data using getStaticProps in NextJS App.
// index.js
export default function Home({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
return {
props: {
data,
},
};
}
Output
How to Fetch data faster in Next.js?
NextJS, a popular React framework provides various approaches to fetch data efficiently. Optimizing data fetching can significantly improve the performance and user experience of your NextJS applications.
We will discuss different approaches to Fetch data faster in NextJS:
Table of Content
- Static Generation using getStaticProps
- Server-side Rendering using getServerSideProps
- Client-side Data Fetching with useSWR and fetch