Implementing infinite scroll in React Native

I’ve seen some solutions for this online, but I can’t get any of them to work.

I have a React Native app which loads data from an API. The data is paginated; each time I retrieve a page, I receive the results for that page, plus the url for the next page. So a typical response from the API is in this format (obviously it’s a bit more complex than this, but this is the gist):

{
  data: [
    { key: xx, title: 'Item 1' },
    { key: yy, title: 'Item 2' }
  ], 
  next: 'www/url/to/next/page/of/results'
}

I want to display each item on screen, and when the user scrolls to the bottom of the screen, the next set of results should load. I’m trying to use a FlatList for this.

So far I have (I don’t have any kind of error checking or anything in yet; just trying to get it to work first):

const HomeScreen = () => {
  const [next, setNext] = React.useState<string>(BASE_URL); // URL of first page of results
  const [isLoading, setIsLoading] = React.useState<boolean>(true);
  const [displayItems, setDisplayItems] = React.useState<Item[]|null>(null);

  // Get next page of items
  const fetchItems = async () => {
    setIsLoading(true);
    const response = await client(next, 'GET'); // Just calls axios
    setDisplayItems((items) => items.concat(response.data));
    setNext(response.next);
    setIsLoading(false);
  };

  // Get items on first loading screen
  React.useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  // Show items
  if (isLoading) return <LoadingSpinner />
  if (displayItems && displayItems.length === 0) return <Text>Nothing to show</Text>
  return <FlatList
        onEndReachedThreshold={0}
        onEndReached={fetchItems}
        data={displayItems}
        renderItem={(i) => <ShowItem item={i}/>} />
    
};

export default HomeScreen;

The problem with this is that it flags an error saying The 'fetchItems' function makes the dependencies of useEffect Hook change on every render.. It suggests To fix this, wrap the definition of 'fetchItems' in its own useCallback() Hook..

So I wrap it in a useCallback() hook:

  const fetchItems = React.useCallback(async () => {
    setIsLoading(true);
    const response = await client(next, 'GET'); // Just calls axios
    setDisplayItems((items) => items.concat(response.data));
    setNext(response.next);
    setIsLoading(false);
  }, [next]);

This doesn’t run at all unless I add fetchItems(), but at that point it re-renders infinitely.

I can’t find anything online that has worked. The annoying thing is that I remember implementing this for another project a few years ago, and I don’t remember it being particularly complicated! Any help appreciated.

For the main error you mentioned in your question:

  1. Without React.useCallback, on each render (or state update), such as setNext(response.next), a new reference of fetchItems is created. This forces the useEffect to be triggered again, causing another call to fetchItems. This creates a loop of infinite API calls and re-renders.
  2. With React.useCallback, since you’ve included next (a state variable) in the dependency array, and next is updated within the fetchItems function, when next is updated, React.useCallback will return a new reference to fetchItems, and thus useEffect will be triggered again.

Simple Solution: Remove fetchItems from the useEffect dependency array to avoid triggering re-renders unnecessarily.

Best Practices:

  • Use useRef instead of useState for next: This prevents unnecessary re-renders, as useRef updates without triggering a re-render, unlike useState.
  • onEndReached should only be called if there is no API call (data fetching) in progress: Implement a flag(isLoading) or condition to ensure you don’t trigger additional fetches while one is already happening.
  • Use keyExtractor: Always ensure a stable and unique key for each list item to help React optimize rendering efficiently.

Here is the sample solution:

import React, {useRef} from 'react';
import {FlatList} from 'react-native';

const HomeScreen = () => {
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [displayItems, setDisplayItems] = useState<Item[] | null>(null);

  const nextRef = useRef(BASE_URL);

  const fetchItems = async () => {
    setIsLoading(true);
    const response = await client(nextRef.current, 'GET'); // Just calls axios
    setDisplayItems((items) => items.concat(response.data));
    nextRef.current = response.next;
    setIsLoading(false);
  };

  React.useEffect(() => {
    fetchItems();
  }, []);

  const onEndReached = () => {
    if (!isLoading) {
      fetchItems()
    }
  }

  const listEmptyComponent = () => {
    if (!isLoading && displayItems?.length === 0) {
      return (
        <Text>Nothing to show</Text>
      )
    }
  }

  const renderItem = ({item}) => {
    return <ShowItem item={item}/>
  }

  const listFooterComponent = () => {
    if (isLoading && displayItems?.length > 0) {
      return <LoadingSpinner/>
    }
  }

  return (
    <FlatList
      data={displayItems}
      onEndReached={onEndReached}
      renderItem={renderItem}
      ListFooterComponent={listFooterComponent}
      ListEmptyComponent={listEmptyComponent}
      keyExtractor={(item) => item.id}
    />
  )

};

export default HomeScreen;

3

The comment on your useEffect suggest that the purpose of that effect is to fetch data on the initial render; so you need to add a conditional to that effect to ensure it does that:

// Get items on first loading screen
  React.useEffect(() => {
    if(displayItems == null) fetchItems();
  }, [fetchItems,displayItems]);

Doing it this way the useEffect is called when fetchItems or displayItems changes, but only calls fetchItems if displayItems is null (its initial state). I dont think its necessary to wrap fetchItems with useCallback, but this effect should work whether fetchItems is wrapped or not

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật