Requesting Data in Next JS
- Client-side: Next.js integrates well with libraries like fetch or axios for making API requests directly from the browser. This approach is ideal for fetching data that doesn’t require server-side processing.
- Server-side: Functions like getStaticProps and getServerSideProps enable you to fetch data on the server before the page is rendered. This is useful for dynamic content that needs to be personalized for each user.
- getStaticProps vs. getServerSideProps:
- getStaticProps: This function fetches data at build time, making your pages statically generated. This is ideal for content that rarely changes and prioritizes fast load times.
- getServerSideProps: This function fetches data on each request, making your pages server-rendered. This provides the most dynamic experience but might have a slight performance overhead compared to getStaticProps.
- Caching Data – Caching stores data so it doesn’t need to be re-fetched from the data source for every request.
- Revalidating Data – Revalidating data is a process of purging the cache data and fetching the latest data. cached data can be revalidated in two ways.
- Time-based revalidation and On-demand revalidation.
Exmaple: Fetching Data with getStaticProps: This example fetches a list of posts from an API and displays them on the page. The getStaticProps function fetches data before the page is rendered on the server.
pages/posts.js
import React from 'react';
export async function getStaticProps() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/');
const data = await response.json();
return {
props: {
posts: data,
},
};
}
export default function Posts({ posts }) {
return (
<div>
<h1>List of Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
Getting Started with Next JS
NextJS is an open-source React framework for building full-stack web applications ( created and maintained by Vercel ). You can use React Components to build user interfaces, and NextJS for additional features and optimizations. It is built on top of Server Components, which allows you to render server-rendered React components to the client. This means your pages can be more interactive and dynamic, while still being fast and performant. One of its notable features is the NextJS App Router, which facilitates routing within your application. This article will dive into NextJS App Router, its components, and implementation, and provide a code example and a brief output.
Table of Content
- What Features NextJS Gives You?
- What Features Does NextJS Not Have?
- What is the NextJS App router?
- How to Create a NextJS App?
- NextJS Scripts
- Add TypeScript to NextJS
- Pages and Routes in Next JS
- Links and Navigation in Next JS
- Route Groups in Next JS
- SEO in Next JS
- API Routes in Next JS
- Data fetching in Next JS
- Requesting Data in Next JS
- Conclusion