Infinite scroll
הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.
בנו feed עם infinite scroll. api.js הוא server מזויף עם 95 פוסטים, שמוחזרים 10 בכל פעם עם השהיה, ו-Post.js מרנדר פוסט אחד. כרגע ה-feed ריק.
const { items, nextCursor } = await fetchPosts({ cursor: 0, limit: 10 })
// nextCursor is the cursor of the next page, or null after the last postדרישות
- טוענים את העמוד הראשון כשה-feed מופיע.
- כשהמשתמש גולל קרוב לתחתית, טוענים את העמוד הבא ומוסיפים אותו לסוף. השתמשו ב-
IntersectionObserver, ולא ב-listener של אירועscroll. - לעולם לא מבקשים את אותו עמוד פעמיים, ולא שולחים בקשה חדשה כשבקשה קודמת עדיין בטעינה.
- בזמן שעמוד נטען, מציגים
Loading more posts.... - שגיאות: ה-API נכשל בפעם הראשונה שמבקשים את עמוד 3. מציגים הודעת שגיאה עם כפתור Retry, ולא מנסים שוב אוטומטית. Retry טוען את העמוד, והגלילה ממשיכה כרגיל.
- אחרי הפוסט האחרון, מציגים
You've reached the end.ומפסיקים לשלוח בקשות.
נגישות
- הודעות הטעינה, השגיאה והסוף נמצאות באזור עם
role="status", כך ש-screen readers מכריזים עליהן.
הערה
ה-preview מתעדכן תוך כדי הקלדה. לאתגר הזה עוד אין בדיקות אוטומטיות: גללו עד הסוף, בדקו את השגיאה ואת ה-retry, ועקבו ב-console אחרי בקשות כפולות. אחר כך השוו לפתרון.
index.js מרנדר את האפליקציה בתוך <StrictMode>, שמריץ effects פעמיים ב-development. ה-feed שלכם עדיין צריך לטעון את עמוד 1 פעם אחת בלבד.
שאלות המשך שמראיינים שואלים
- עכשיו יש ב-feed עשרת אלפים פוסטים. מה קורה ל-DOM, ואיך virtualization פותר את זה?
- לשחזר את מיקום הגלילה כשהמשתמש נכנס לפוסט וחוזר.
- להפוך את הלוגיקה ל-hook רב-פעמי בשם
useInfiniteScroll. - כדאי להשתמש כאן ב-
AbortController? מה הוא היה מבטל?
הגישה
ה-state מתאר איפה ה-feed נמצא:
posts: כל מה שנטען עד עכשיו.cursor: העמוד הבא שצריך לבקש, אוnullכשלא נשאר כלום.status:idle,loadingאוerror.
<div> בלתי נראה, sentinel, יושב אחרי הפוסט האחרון. IntersectionObserver עוקב אחריו, וכשהוא מגיע ל-200px מה-viewport, loadMore() רצה. אין קוד נפרד של "לטעון את העמוד הראשון ב-mount": כשאין פוסטים, ה-sentinel כבר על המסך, כך שה-observer מפעיל גם את הטעינה הראשונה.
בלי בקשות כפולות
ה-guard הוא ref, loadingRef, ולא ה-state status. עדכוני state מופיעים רק ב-render הבא, כך ששתי קריאות באותו tick (ה-observer שנורה פעמיים, או StrictMode שמריץ את ה-effect פעמיים) היו קוראות שתיהן status === 'idle' ושולחות שתיהן בקשה. ref משתנה מיד, ולכן הקריאה השנייה יוצאת מוקדם.
למה ה-observer נוצר מחדש
loadMore קוראת את cursor, ולכן היא משתנה אחרי כל עמוד, וה-effect רץ מחדש עם ה-loadMore החדשה. ל-observe מחדש יש תופעת לוואי שימושית: IntersectionObserver מדווח על המצב הנוכחי מיד כשהוא מתחיל לעקוב. אם העמוד החדש קצר מכדי לדחוף את ה-sentinel מחוץ למסך, ה-observer נורה שוב וטוען עמוד נוסף, עד שהמסך מתמלא.
שגיאות והסוף
- ב-
error, ה-effect לא יוצר observer. ה-feed מחכה שהמשתמש ילחץ Retry, במקום לנסות שוב בלולאה מול server שנכשל. - כש-
cursorהואnull, גם אז ה-observer לא נוצר, ולכן לא נשלחות עוד בקשות.
למה לא listener של scroll
handler של scroll רץ על ה-main thread עשרות פעמים בשנייה וצריך למדוד layout (scrollHeight, getBoundingClientRect) בכל פעם, מה שגורם ל-reflow. IntersectionObserver מחושב על ידי הדפדפן מחוץ ל-critical path וקורא לכם רק כשה-visibility באמת משתנה.
מה מראיינים מחפשים
IntersectionObserverעם sentinel ו-rootMargin.- guard סינכרוני לבקשה שבדרך, והיכולת להסביר למה state לבד לא מספיק.
- מצבי loading, error עם retry ידני, וסוף הרשימה.
- ניקוי ה-observer.
- לדעת מתי צריך virtualization.
פתרון לדוגמה
src/App.js
import { useCallback, useEffect, useRef, useState } from 'react'
import { fetchPosts } from './api'
import Post from './Post'
const PAGE_SIZE = 10
export default function App() {
const [posts, setPosts] = useState([])
// The cursor of the next page to load; null once the last page has loaded.
const [cursor, setCursor] = useState(0)
const [status, setStatus] = useState('idle') // 'idle' | 'loading' | 'error'
const loadingRef = useRef(false)
const sentinelRef = useRef(null)
const loadMore = useCallback(async () => {
// A ref, not state: two calls in the same tick both see it immediately.
if (loadingRef.current || cursor === null) return
loadingRef.current = true
setStatus('loading')
try {
const page = await fetchPosts({ cursor, limit: PAGE_SIZE })
setPosts((current) => [...current, ...page.items])
setCursor(page.nextCursor)
setStatus('idle')
} catch {
setStatus('error')
} finally {
loadingRef.current = false
}
}, [cursor])
useEffect(() => {
const sentinel = sentinelRef.current
// After an error, wait for Retry instead of hammering the server.
if (!sentinel || status === 'error' || cursor === null) return
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) loadMore()
},
// Start loading a little before the user actually reaches the bottom.
{ rootMargin: '200px' },
)
observer.observe(sentinel)
return () => observer.disconnect()
}, [loadMore, status, cursor])
return (
<main className="feed">
<h1>Feed</h1>
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
<div ref={sentinelRef} aria-hidden="true" />
<div className="status" role="status">
{status === 'loading' && 'Loading more posts...'}
{status === 'error' && (
<>
Couldn't load more posts.
<button type="button" onClick={loadMore}>
Retry
</button>
</>
)}
{cursor === null && "You've reached the end."}
</div>
</main>
)
}