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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A cursor plus a sentinel element turns scroll position into a clean pagination trigger without scroll math.
- 2Wrapping the async fetch in a transition keeps the appended list from blocking the UI while showing pending state.
- 3Cleaning up the observer on effect teardown prevents duplicate fetches and memory leaks across re-renders.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
javascript
import { useState, useCallback, useRef } from 'react'; function LikeButton({ postId, initialLiked, initialCount }) { const [liked, setLiked] = useState(initialLiked);
Optimistic like button with React
optimistic-ui
abortcontroller
error-handling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/infinite-scroll-with-server-actions-in-next-js-explained-javascript-2f28/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.