Hard
React Infinite Scroll Performance: Fix Missing Dependencies in useEffect Hook
In a news website's infinite scroll implementation, you need to handle scroll events efficiently and prevent duplicate API calls. What's the issue with this code?
1function NewsTimeline() {2 const [articles, setArticles] = useState([]);3 const [page, setPage] = useState(1);4 const [isLoading, setIsLoading] = useState(false);5 const [hasMore, setHasMore] = useState(true);67 const loadMoreArticles = async () => {8 if (!hasMore || isLoading) return;910 setIsLoading(true);11 try {12 const response = await fetch(`/api/articles?page=${page}`);13 const data = await response.json();14 setArticles(prev => [...prev, ...data.articles]);15 setHasMore(data.hasMore);16 setPage(prev => prev + 1);17 } catch (error) {18 console.error('Failed to load articles:', error);19 }20 setIsLoading(false);21 };2223 useEffect(() => {24 const handleScroll = () => {25 if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 500) {26 loadMoreArticles();27 }28 };2930 window.addEventListener('scroll', handleScroll);31 return () => window.removeEventListener('scroll', handleScroll);32 }, []);3334 return (35 <div className="timeline">36 {articles.map(article => (37 <ArticleCard key={article.id} article={article} />38 ))}39 {isLoading && <LoadingSpinner />}40 </div>41 );42}