javascript 50 lines · 8 steps

Infinite scroll with Server Actions in Next.js

A client component pairs an IntersectionObserver sentinel with a Server Action to append posts as the user scrolls.

Explained by highlit
1'use client';
2 
3import { useState, useTransition, useRef, useEffect, useCallback } from 'react';
4import { loadMorePosts } from '@/app/actions/posts';
5import { PostCard } from '@/components/post-card';
6 
7export function PostFeed({ initialPosts, initialCursor }) {
8 const [posts, setPosts] = useState(initialPosts);
9 const [cursor, setCursor] = useState(initialCursor);
10 const [isPending, startTransition] = useTransition();
11 const sentinelRef = useRef(null);
12 
13 const loadMore = useCallback(() => {
14 if (!cursor || isPending) return;
15 startTransition(async () => {
16 const { posts: next, nextCursor } = await loadMorePosts(cursor);
17 setPosts((prev) => [...prev, ...next]);
18 setCursor(nextCursor);
19 });
20 }, [cursor, isPending]);
21 
22 useEffect(() => {
23 const node = sentinelRef.current;
24 if (!node) return;
25 
26 const observer = new IntersectionObserver(
27 ([entry]) => {
28 if (entry.isIntersecting) loadMore();
29 },
30 { rootMargin: '400px' }
31 );
32 
33 observer.observe(node);
34 return () => observer.disconnect();
35 }, [loadMore]);
36 
37 return (
38 <div className="flex flex-col gap-4">
39 {posts.map((post) => (
40 <PostCard key={post.id} post={post} />
41 ))}
42 
43 {cursor && (
44 <div ref={sentinelRef} className="py-8 text-center text-sm text-gray-500">
45 {isPending ? 'Loading more\u2026' : ''}
46 </div>
47 )}
48 </div>
49 );
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A cursor plus a sentinel element turns scroll position into a clean pagination trigger without scroll math.
  2. 2Wrapping the async fetch in a transition keeps the appended list from blocking the UI while showing pending state.
  3. 3Cleaning up the observer on effect teardown prevents duplicate fetches and memory leaks across re-renders.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Infinite scroll with Server Actions in Next.js — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code