Next.js 14 : 3 ways to fetch data from API

Next.js provides a variety of methods and techniques for data fetching, enabling you to select the most suitable approach based on your application's requirements. These data fetching techniques play ...
MOHAMMED DAKIR| January 10, 2024
Next.js 14 : 3 ways to fetch data from API

#Next.js #webDev #javascript #API #data

Data fetching is a core part of any application. This page goes through how you can fetch, cache, and revalidate data in React and Next.js.

There are four ways you can fetch data:

On the server, with fetch :

Next.js extends the native fetch Web API

 to allow you to configure the caching and revalidating behavior for each fetch request on the server. React extends fetch to automatically memoize fetch requests while rendering a React component tree.

You can use fetch with async/await in Server Components, in Route Handlers, and in Server Actions.

For example:

async function getData() {
 const res = await fetch('')
 // The return value is *not* serialized
 // You can return Date, Map, Set, etc.
 if (!res.ok) {
  // This will activate the closest `error.js` Error Boundary
  throw new Error('Failed to fetch data')
 return res.json()
export default async function Page() {
 const data = await getData()
 return <main></main>

Fetching data on the Server with third-party libraries :

In cases where you're using a third-party library that doesn't support or expose fetch (for example, a database, CMS, or ORM client), you can configure the caching and revalidating behavior of those requests using the Route Segment Config Option and React's cache function.

Whether the data is cached or not will depend on whether the route segment is statically or dynamically rendered. If the segment is static (default), the output of the request will be cached and revalidated as part of the route segment. If the segment is dynamic, the output of the request will not be cached and will be re-fetched on every request when the segment is rendered.


In the example below:

  • The React cache function is used to memoize data requests.
  • The revalidate option is set to 3600 in the Layout and Page segments, meaning the data will be cached and revalidated at most every hour.
import { cache } from 'react'
export const getItem = cache(async (id) => {
 const item = await db.item.findUnique({ id })
 return item

Although the getItem function is called twice, only one query will be made to the database.

import { getItem } from '@/utils/get-item'
export const revalidate = 3600 // revalidate the data at most every hour
export default async function Layout({ params: { id } }) {
 const item = await getItem(id)
 // ...

import { getItem } from '@/utils/get-item'
export const revalidate = 3600 // revalidate the data at most every hour
export default async function Page({ params: { id } }) {
 const item = await getItem(id)
 // ...

fetch data on the Client side:

Client Components allows you to write interactive UI that can be rendered on the client at request time. In Next.js, client rendering is opt-in, meaning you have to explicitly decide what components React should render on the client.

This page will go through how Client Components work, how they're rendered, and when you might use them.

for example :

"use client";
import React, { useState, useEffect } from "react";

export default function Home() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
      .then((res) => res.json())
      .then((data) => {
        const sortedPosts = data?.sort(
          (a, b) => new Date(b.createdAt) - new Date(a.createdAt)
  }, []);
  return (
    <section className="">
       //display your data here

That's it for today guys

As always, I'm looking forward to hearing your thoughts in the comments section. Feel free to share your insights and experiences with these different data fetching patterns.

This website uses cookies to enhance your browsing experience, analyze site traffic, and serve better user experiences. By continuing to use this site, you consent to our use of cookies. Learn more in our cookie policy

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policy