Claude Code के साथ Implement Infinite Scroll कैसे करें
Claude Code का उपयोग करके implement infinite scroll सीखें। Practical code examples और step-by-step guidance शामिल है।
無限scrollの仕組み
無限scrollは、userがpage末尾に近づくと自動的にअगलाのdataを読み込むUIpattern है।SNSやニュースアプリでおなじみですが、performanceやaccessibilityを考慮したimplementationは意बाहरと難しい चीज़ है।Claude Code से、ベストプラクティスに沿ったimplementationを素早くbuild किया जा सकता है。
Intersection Observerを使った基本implementation
> Intersection Observerを使った無限scrollのReacthookを作って。
> ローディング状態とerror handlingも含めて。
import { useEffect, useRef, useState, useCallback } from 'react';
interface UseInfiniteScrollOptions<T> {
fetchFn: (page: number) => Promise<{ data: T[]; hasMore: boolean }>;
initialPage?: number;
threshold?: number;
}
function useInfiniteScroll<T>({ fetchFn, initialPage = 1, threshold = 0.8 }: UseInfiniteScrollOptions<T>) {
const [items, setItems] = useState<T[]>([]);
const [page, setPage] = useState(initialPage);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const [error, setError] = useState<Error | null>(null);
const observerRef = useRef<IntersectionObserver | null>(null);
const lastElementRef = useCallback(
(node: HTMLElement | null) => {
if (loading) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore) {
setPage((prev) => prev + 1);
}
},
{ threshold }
);
if (node) observerRef.current.observe(node);
},
[loading, hasMore, threshold]
);
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(null);
fetchFn(page)
.then((result) => {
if (!cancelled) {
setItems((prev) => [...prev, ...result.data]);
setHasMore(result.hasMore);
}
})
.catch((err) => { if (!cancelled) setError(err); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [page, fetchFn]);
return { items, loading, hasMore, error, lastElementRef };
}
componentでの使用例
function ArticleList() {
const fetchArticles = useCallback(async (page: number) => {
const res = await fetch(`/api/articles?page=${page}&limit=20`);
const data = await res.json();
return { data: data.articles, hasMore: data.hasMore };
}, []);
const { items, loading, hasMore, error, lastElementRef } = useInfiniteScroll({
fetchFn: fetchArticles,
});
return (
<div role="feed" aria-busy={loading} aria-label="記事list">
{items.map((article, index) => (
<article
key={article.id}
ref={index === items.length - 1 ? lastElementRef : null}
aria-posinset={index + 1}
aria-setsize={hasMore ? -1 : items.length}
>
<h2>{article.title}</h2>
<p>{article.summary}</p>
</article>
))}
{loading && <div aria-live="polite">読み込みमें...</div>}
{error && <div role="alert">errorが発生し हुआ।再試行して करें।</div>}
{!hasMore && <p>सभीの記事 displayし हुआ।</p>}
</div>
);
}
バックエンドのカーソルベースpageネーション
// オフセットベースよりもカーソルベースの方がperformanceがअच्छा
app.get('/api/articles', async (req, res) => {
const limit = Math.min(Number(req.query.limit) || 20, 100);
const cursor = req.query.cursor as string | undefined;
const where = cursor ? { id: { gt: cursor } } : {};
const articles = await prisma.article.findMany({
where,
take: limit + 1,
orderBy: { id: 'asc' },
});
const hasMore = articles.length > limit;
const data = hasMore ? articles.slice(0, -1) : articles;
res.json({
data,
hasMore,
nextCursor: hasMore ? data[data.length - 1].id : null,
});
});
Summary
Claude Code का उपयोग करके、Intersection Observerベースの無限scroll सेカーソルベースAPI तक一貫してbuild किया जा सकता है。大量dataの描画performanceには仮想scrollimplementationを、pageネーション方式の比較はpageネーションimplementationをदेखें。
Intersection Observer APIके details के लिएMDN Web Docsदेखें。
Related Posts
Claude Code से Productivity 3 गुना बढ़ाने की 10 Tips
Claude Code से ज़्यादा पाने की 10 practical tips जानें। Prompt strategies से workflow shortcuts तक, ये techniques आज से ही आपकी efficiency boost करेंगी।
Claude Code के साथ Canvas/WebGL Optimization
Claude Code का उपयोग करके Canvas/WebGL optimization के बारे में जानें। Practical tips और code examples शामिल हैं।
Claude Code के साथ Markdown Implementation
Claude Code का उपयोग करके markdown implementation सीखें। Practical tips और code examples शामिल हैं।