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:
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('https://api.example.com/...')
// 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>
}
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:
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)
// ...
}
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(() => {
setLoading(true);
fetch("/api/articles")
.then((res) => res.json())
.then((data) => {
const sortedPosts = data?.sort(
(a, b) => new Date(b.createdAt) - new Date(a.createdAt)
);
setPosts(sortedPosts);
setLoading(false);
});
}, []);
return (
<section className="">
//display your data here
</section>
);
}
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