Next.js Data Fetching
Next.js provides multiple data-fetching approaches, allowing you to fetch and present data at different rendering stages (for example, server-side rendering, static generation, and client-side rendering).
Client-Side Data Fetching
Sometimes you want to fetch data from the client after the page loads, rather than at build time or on the server. You can use React's useEffect hook to handle client-side data fetching.
Using useEffect and fetch
Use the useEffect hook and the fetch API in a React component to fetch data.
useEffect runs after the component mounts, where you can make an API request and update state.
app/posts/page.tsx file code:
// app/posts/page.tsx
'use client'
;
import
{
useEffect
,
useState
}
from
'react'
;
export
default
function
PostsPage
(
)
{
const
[
posts
,
setPosts
]
=
useState
(
[
]
)
;
useEffect
(
(
)
=>
{
const
fetchPosts
=
async
(
)
=>
{
const
res
=
await fetch
(
'https://jsonplaceholder.typicode.com/posts'
)
;
const
data
=
await res.
json
(
)
;
setPosts
(
data
)
;
}
;
fetchPosts
(
)
;
}
,
[
]
)
;
return
(
<
div
<
h1RUNOOB Test
</
h1
<
ul
{posts.
map
(
post
=>
(
<
li key
=
{
post.
id
}
{
post.
title
}
</
li
)
)
}
</
ul
</
div
);
}
Visit http://localhost:3000/posts; the displayed structure is as follows:

useEffect runs after client-side rendering and is suitable for client-rendered data.
- Fetching data on the client is suitable for content that does not need server-side rendering.
- Data can be fetched dynamically based on factors such as user interaction or time.
Use cases:
- Dynamically loaded data, such as infinite scroll or pagination.
- Data fetched only after a user action, such as after clicking a button.
Server-Side Data Fetching
Server-side data can be fetched using the following approaches:
- fetch API
- ORM or Database
Using the fetch API
To use the fetch API to fetch data, you need to convert your component into an async function and use await to wait for the fetch call. An example follows:
app/posts/page.tsx file code:
// app/posts/page.tsx
export
default
async
function
Page
(
)
{
const
data
=
await fetch
(
'https://jsonplaceholder.typicode.com/posts'
)
const
posts
=
await data.
json
(
)
return
(
<
ul
{posts.
map
(
(
post
)
=>
(
<
li key
=
{
post.
id
}
{
post.
title
}
</
li
)
)
}
</
ul
)
}You can also fetch data via an ORM or database; simply convert the component into an async function and await the database call:
app/posts/page.tsx file code:
// app/posts/page.tsx
import
{
db
,
posts
}
from
'@/lib/db'
export
default
async
function
Page
(
)
{
const
allPosts
=
await db.
select
(
)
.
from
(
posts
)
return
(
<
ul
{allPosts.
map
(
(
post
)
=>
(
<
li key
=
{
post.
id
}
{
post.
title
}
</
li
)
)
}
</
ul
)
}