Bird
Raised Fist0
React Nativemobile~20 mins

Infinite scrolling (onEndReached) in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Infinite Scroll List
A screen that shows a list of items and loads more items automatically when the user scrolls to the bottom.
Target UI
-------------------------
| Infinite Scroll List   |
-------------------------
| Item 1                |
| Item 2                |
| Item 3                |
| ...                   |
| Loading more...       |
-------------------------
Display a scrollable list of items with initial 20 items labeled 'Item 1' to 'Item 20'.
When the user scrolls near the bottom, automatically load 20 more items and append to the list.
Show a loading indicator at the bottom while loading more items.
Use FlatList component with onEndReached to detect scrolling near the end.
Ensure no duplicate items and smooth scrolling experience.
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, ActivityIndicator, StyleSheet } from 'react-native';

export default function InfiniteScrollList() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // TODO: Load initial 20 items here
  }, []);

  const loadMore = () => {
    // TODO: Load 20 more items and update data
  };

  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' },
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
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.

Final Result
Completed Screen
-------------------------
| Infinite Scroll List   |
-------------------------
| Item 1                |
| Item 2                |
| Item 3                |
| ...                   |
| Item 40               |
| Loading more...       |
-------------------------
User scrolls down the list.
When near bottom, new items (e.g., Item 21 to Item 40) load automatically.
Loading spinner appears at bottom while loading.
List grows smoothly with new items appended.
Stretch Goal
Add a pull-to-refresh feature to reload the list from the start.
💡 Hint
Use FlatList's refreshing and onRefresh props to implement pull-to-refresh.

Practice

(1/5)
1.

What is the main purpose of the onEndReached prop in a React Native FlatList?

easy
A. To detect when the user scrolls near the end of the list to load more items
B. To refresh the list when the user pulls down
C. To set the initial number of items displayed
D. To style the list footer component

Solution

  1. Step 1: Understand onEndReached role

    This prop triggers a function when the user scrolls near the end of the list.
  2. Step 2: Compare with other options

    Refreshing is handled by onRefresh, initial items by initialNumToRender, and styling is unrelated.
  3. Final Answer:

    To detect when the user scrolls near the end of the list to load more items -> Option A
  4. Quick Check:

    onEndReached triggers loading more [OK]
Hint: Remember: onEndReached means near list end, load more [OK]
Common Mistakes:
  • Confusing onEndReached with pull-to-refresh
  • Thinking it controls initial render count
  • Assuming it styles the list footer
2.

Which of the following is the correct way to use onEndReached in a FlatList?

<FlatList
  data={data}
  renderItem={renderItem}
  onEndReached={_____}
/>
easy
A. onEndReached()
B. loadMoreItems()
C. () => loadMoreItems
D. loadMoreItems

Solution

  1. Step 1: Understand event handler syntax

    onEndReached expects a function, so we pass a function reference or an arrow function.
  2. Step 2: Analyze options

    onEndReached() ("onEndReached()") calls an undefined function immediately. loadMoreItems() ("loadMoreItems()") executes immediately on render. () => loadMoreItems ("() => loadMoreItems") returns the function but does not call it when triggered. loadMoreItems ("loadMoreItems") passes the correct function reference.
  3. Final Answer:

    loadMoreItems -> Option D
  4. Quick Check:

    Pass a function reference, not call it immediately [OK]
Hint: Pass function reference `loadMoreItems`, not `loadMoreItems()` [OK]
Common Mistakes:
  • Calling the function immediately instead of passing it
  • Passing undefined or wrong function name
  • Confusing function reference with function call
3.

Given this code snippet, what will happen when the user scrolls near the end of the list?

const [items, setItems] = React.useState([1, 2, 3]);
const loadMore = () => {
  setItems(prev => [...prev, prev.length + 1]);
};

return (
  <FlatList
    data={items}
    renderItem={({item}) => <Text>Item {item}</Text>}
    keyExtractor={item => item.toString()}
    onEndReached={loadMore}
  />
);
medium
A. The list will add one new item each time the end is reached
B. The list will reset to only one item
C. The list will not change because loadMore is not called
D. The app will crash due to infinite loop

Solution

  1. Step 1: Understand loadMore function

    It adds a new item with value one greater than current length to the items array.
  2. Step 2: Analyze onEndReached effect

    When user scrolls near the end, loadMore is called, so items grow by one each time.
  3. Final Answer:

    The list will add one new item each time the end is reached -> Option A
  4. Quick Check:

    onEndReached triggers loadMore which appends items [OK]
Hint: onEndReached calls loadMore, which adds one item [OK]
Common Mistakes:
  • Thinking the list resets instead of appending
  • Assuming loadMore is not called automatically
  • Expecting a crash without seeing infinite state updates
4.

What is the main problem with this infinite scrolling implementation?

const [items, setItems] = React.useState([1, 2, 3]);
const loadMore = () => {
  setItems(prev => [...prev, prev.length + 1]);
};

return (
  <FlatList
    data={items}
    renderItem={({item}) => <Text>Item {item}</Text>}
    keyExtractor={item => item.toString()}
    onEndReached={loadMore}
    onEndReachedThreshold={0.1}
  />
);

Assume the list is short and the user scrolls to the bottom.

medium
A. The keyExtractor will cause duplicate keys error
B. The list will never load more items because onEndReachedThreshold is too low
C. loadMore will be called repeatedly causing many state updates and possible performance issues
D. The renderItem function is missing a return statement

Solution

  1. Step 1: Understand onEndReached behavior

    When the list is short, scrolling near the end triggers loadMore repeatedly because the end is always near.
  2. Step 2: Identify consequence

    This causes many state updates rapidly, which can cause performance problems or infinite loops.
  3. Final Answer:

    loadMore will be called repeatedly causing many state updates and possible performance issues -> Option C
  4. Quick Check:

    Repeated onEndReached calls cause performance issues [OK]
Hint: Short lists cause repeated onEndReached calls without loading guard [OK]
Common Mistakes:
  • Ignoring repeated calls without loading state
  • Blaming keyExtractor or renderItem incorrectly
  • Thinking threshold prevents repeated calls
5.

You want to implement infinite scrolling with a loading spinner at the bottom. Which approach correctly prevents multiple loadMore calls while loading?

const [items, setItems] = React.useState([]);
const [loading, setLoading] = React.useState(false);

const loadMore = async () => {
  if (loading) return;
  setLoading(true);
  const newItems = await fetchMoreItems();
  setItems(prev => [...prev, ...newItems]);
  setLoading(false);
};

return (
  <FlatList
    data={items}
    renderItem={({item}) => <Text>{item}</Text>}
    keyExtractor={item => item.id}
    onEndReached={loadMore}
    ListFooterComponent={loading ? <ActivityIndicator /> : null}
  />
);

What is the key reason this works well?

hard
A. It uses ListFooterComponent to prevent scrolling
B. It uses a loading state to block new calls until the current load finishes
C. It resets items to empty before loading new ones
D. It calls fetchMoreItems synchronously to avoid delays

Solution

  1. Step 1: Identify loading state role

    The loading state prevents loadMore from running if a load is already in progress.
  2. Step 2: Understand async loading and UI feedback

    While loading, the spinner shows in the footer, and new calls are blocked until loading finishes.
  3. Final Answer:

    It uses a loading state to block new calls until the current load finishes -> Option B
  4. Quick Check:

    Loading state blocks repeated calls during fetch [OK]
Hint: Use loading flag to block repeated loads and show spinner [OK]
Common Mistakes:
  • Not blocking repeated calls causing multiple fetches
  • Calling fetchMoreItems synchronously (wrong)
  • Misusing ListFooterComponent to block scrolling
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard