Next.js is a React framework that enhances UI development with built-in features like server-side rendering and static site generation. It supports data fetching both on the server and client sides, enabling developers to load and manage data efficiently. By utilizing functions like fetch, Next.js allows for data fetching, enhancing the interactivity and responsiveness of web applications.
Fetch Function
The fetch function is a modern JavaScript API used to make HTTP requests. It returns a Promise that resolves to the Response object representing the response to the request. With fetch, you can perform GET, POST, and other HTTP operations, and process the response data using methods like .json() to handle JSON data. It is commonly used for client-side data fetching in web applications.
Syntax:
fetch(url, [options])
.then(response => response.json()) // or response.text() for text responses
.then(data => {
// handling the data
})
.catch(error => {
// handling any errors
});
Steps to Create NextJS Application and using Fetch Function
Step 1: Create a Next.js application using the following command.
npx create-next-app@latest gfg
Step 2: It will ask you some questions, so choose the following.
√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to customize the default import alias (@/*)? ... Yes
Step 3: After creating your project folder i.e. gfg, move to it using the following command.
cd gfg
Folder Structure

Dependencies
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
},
Example: This demonstrate Next.js client-side functionality to fetch data. The fetchData function retrieves a random post from an API each time the button is clicked. We manage the loading, error, and fetched data states to provide a responsive user experience.
JavaScript
// src/app/page.js
"use client";
import { useState } from 'react';
export default function HomePage() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const randomId =
Math.floor(Math.random() * 100) + 1;
const response =
await fetch(`
https://jsonplaceholder.typicode.com/posts/${randomId}`);
if (!response.ok) {
throw new Error('
Network response was not ok');
}
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
return (
<main style={{ padding: '16px' }}>
<h1 style={{ fontSize: '24px',
fontWeight: 'bold', color: 'green' }}>
GeeksforGeeks
</h1>
<h3 style={{ fontSize: '20px',
marginTop: '16px' }}>
NextJS: Fetch Function
</h3>
<button
onClick={fetchData}
style={{ padding: '10px 20px',
fontSize: '16px', marginTop: '16px',
backgroundColor: 'blue', color: 'white',
border: 'none', borderRadius: '5px' }}
>
Fetch New Data
</button>
{loading && <p>Loading...</p>}
{error && <p style={{ color: 'red' }}>
Error: {error.message}</p>}
{data && (
<div style={{ marginTop: '16px' }}>
<h4>Fetched Data:</h4>
<p><strong>
Title:</strong> {data.title}</p>
<p><strong>
Body:</strong> {data.body}</p>
</div>
)}
</main>
);
}
Output:
Options in Fetch Option
Options.cache
Controls how the fetch request utilizes the browser cache. Possible values include 'default', 'no-store', 'reload', 'no-cache', 'force-cache', and 'only-if-cached'.
Syntax:
fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
Example: In this example we fetches data from a JSON placeholder API using the cache: 'force-cache' option, ensuring the response is always retrieved from the cache if available. The fetched data is then displayed.
JavaScript
// src/app/page.js
"use client";
import React, { useEffect, useState } from 'react';
const Page = () => {
const [post, setPost] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/1`, {
cache: 'force-cache'
});
const data = await response.json();
setPost(data);
};
fetchData();
}, []);
return (
<div>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3 style={{ color: 'black' }}>Cache Option</h3>
{post && (
<div>
<h3 style={{ color: 'black' }}>Post Title</h3>
<p>{post.title}</p>
<h3 style={{ color: 'black' }}>Post Body</h3>
<p>{post.body}</p>
</div>
)}
</div>
);
};
export default Page;
Output:
OutputOptions.next.revalidate
Specifies the number of seconds after which the cached response should be revalidated. This ensures the content stays up-to-date based on the provided duration.
Syntax:
fetch(`https://...`, { next: { revalidate: false | 0 | number } })
Example: The below example fetches data from a JSON placeholder API with a revalidate: 10 option, ensuring the response is revalidated every 10 seconds. It includes a button to manually refetch the data and displays the last fetched time to show the revalidation behavior.
JavaScript
// src/app/page.js
"use client";
import React, { useEffect, useState } from 'react';
const Page = () => {
const [post, setPost] = useState(null);
const [lastFetched, setLastFetched] = useState(null);
const fetchData = async () => {
const response = await fetch(`
https://jsonplaceholder.typicode.com/posts/2`, {
next: {
revalidate: 10 // Revalidate after 10 seconds
}
});
const data = await response.json();
setPost(data);
setLastFetched(new Date().toLocaleTimeString());
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3 style={{ color: 'black' }}>Revalidate Option</h3>
<button onClick={fetchData}>Refetch Post</button>
{post && (
<div>
<h3 style={{ color: 'black' }}>Post Title</h3>
<p>{post.title}</p>
<h3 style={{ color: 'black' }}>Post Body</h3>
<p>{post.body}</p>
<h3 style={{ color: 'black' }}>Last Fetched</h3>
<p>{lastFetched}</p>
</div>
)}
</div>
);
};
export default Page;
Output:
OutputOptions.next.tags
Allows tagging of the fetch request for easier cache invalidation and management. Tags can be used to group and invalidate multiple requests simultaneously.
Syntax:
fetch(`https://...`, { next: { tags: ['collection'] } })
Example: The component fetches and displays a post from an API based on dynamic tags. Users can add or remove tags, triggering a re-fetch of the data each time the tags change. The component demonstrates the use of options.next.tags for easier cache invalidation and management.
JavaScript
// src/app/page.js
"use client";
import React, { useEffect, useState } from 'react';
const PageWithTags = () => {
const [post, setPost] = useState(null);
const [tags, setTags] = useState(['post', 'tagged-fetch']);
const [newTag, setNewTag] = useState('');
const fetchData = async () => {
const response = await fetch('
https://jsonplaceholder.typicode.com/posts/3', {
next: {
tags: tags,
},
});
const data = await response.json();
setPost(data);
};
useEffect(() => {
fetchData();
}, [tags]);
const handleAddTag = () => {
if (newTag && !tags.includes(newTag)) {
setTags([...tags, newTag]);
setNewTag('');
}
};
const handleRemoveTag = (tagToRemove) => {
setTags(tags.filter(tag => tag !== tagToRemove));
};
return (
<div>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3 style={{ color: 'black' }}>Tags Option</h3>
<div>
<input
type="text"
value={newTag}
onChange={(e) => setNewTag(e.target.value)}
placeholder="Add a new tag"
/>
<button onClick={handleAddTag}>Add Tag</button>
</div>
<div>
<h4>Current Tags:</h4>
{tags.map((tag, index) => (
<span key={index} style={{ marginRight: '10px' }}>
{tag}
<button onClick={() =>
handleRemoveTag(tag)}
style={{ marginLeft: '5px' }}>
Remove</button>
</span>
))}
</div>
{post && (
<div>
<h3 style={{ color: 'black' }}>Post Title</h3>
<p>{post.title}</p>
<h3 style={{ color: 'black' }}>Post Body</h3>
<p>{post.body}</p>
</div>
)}
</div>
);
};
export default PageWithTags;
Output:
Output
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read