import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, FlatList, ActivityIndicator, StyleSheet } from 'react-native';
export default function InfiniteScrollList() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
useEffect(() => {
loadMore();
}, []);
const loadMore = useCallback(() => {
if (loading) return;
setLoading(true);
setTimeout(() => {
const newItems = [];
const start = (page - 1) * 20 + 1;
for (let i = start; i < start + 20; i++) {
newItems.push(`Item ${i}`);
}
setData(prevData => [...prevData, ...newItems]);
setPage(prevPage => prevPage + 1);
setLoading(false);
}, 1000); // simulate network delay
}, [loading, page]);
const renderItem = ({ item }) => <Text style={styles.item}>{item}</Text>;
return (
<View style={styles.container}>
<FlatList
data={data}
keyExtractor={(item) => item}
renderItem={renderItem}
onEndReached={loadMore}
onEndReachedThreshold={0.5}
ListFooterComponent={loading ? <ActivityIndicator size="small" /> : null}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, paddingTop: 50 },
item: { padding: 20, borderBottomWidth: 1, borderColor: '#ccc' },
});This solution uses React Native's FlatList to display a list of items. Initially, it loads 20 items labeled 'Item 1' to 'Item 20'.
The loadMore function adds 20 more items each time it is called, simulating a network delay with setTimeout. It uses a loading state to avoid multiple loads at once.
The onEndReached prop triggers loadMore when the user scrolls near the bottom. A loading spinner shows at the bottom while loading more items.
This creates a smooth infinite scrolling experience without duplicates.