Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 71 ยท Lists

SectionList, Pull to Refresh and Infinite Scroll

Group rows with SectionList and sticky headers, add pull to refresh with RefreshControl, and load more pages with onEndReached without duplicate requests.

A plain FlatList shows one flat sequence of rows. Real apps often need more: contacts grouped by letter, a settings screen with titled groups, a feed that refreshes when you pull down and keeps loading as you scroll. React Native has components and props for each of these. This lesson covers SectionList for grouped data, RefreshControl for pull to refresh, and onEndReached for infinite scroll, including the bugs everyone hits the first time (duplicate page loads and refresh spinners that never stop).

Read-only and stand-in. SectionList and RefreshControl need native scrolling, so the real code is in plain blocks. The TryIts group data with plain JavaScript, use CSS sticky headers to mimic the sticky section header, and run a paginated loader against a fake API with a delay, so the logic can be inspected safely.

SectionList: grouped data

SectionList works like FlatList, but data becomes sections: an array of objects, each with its own data array and any extra fields (usually a title). You tell it how to draw rows and headers:

TSX
import { SectionList, Text, View } from 'react-native';

type Contact = { id: string; name: string };
type Section = { title: string; data: Contact[] };

const sections: Section[] = [
  { title: 'A', data: [{ id: '1', name: 'Ada' }, { id: '2', name: 'Alan' }] },
  { title: 'B', data: [{ id: '3', name: 'Barbara' }] },
];

export function Contacts() {
  return (
    <SectionList
      sections={sections}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => (
        <Text style={{ padding: 12 }}>{item.name}</Text>
      )}
      renderSectionHeader={({ section }) => (
        <Text style={{ padding: 8, fontWeight: '700', backgroundColor: '#f1f5f9' }}>
          {section.title}
        </Text>
      )}
    />
  );
}

All the FlatList ideas carry over: keys must be stable strings, rows should be cheap and memoized (see Fast Lists), and separators, header, footer and empty slots exist (ItemSeparatorComponent, SectionSeparatorComponent, ListHeaderComponent, ListFooterComponent, ListEmptyComponent). Two things are new:

  • renderSectionHeader and renderSectionFooter receive { section }, which is the object you passed, so your own fields (a count, an icon) are available.
  • stickySectionHeadersEnabled pins the current header to the top while its rows scroll beneath it. The default is on for iOS and off for Android, so set it explicitly if you want the same behavior on both. A sticky header needs an opaque background, otherwise rows show through it.

A section can have a different renderItem or keyExtractor of its own, which is useful for mixed content (a "Featured" section of cards followed by plain rows), but start with one shared renderer.

Building sections from a flat array

Server data usually comes flat. Group it before it reaches the list, and do it in useMemo so the grouping does not repeat on each render:

TSX
const sections = useMemo(() => groupByInitial(contacts), [contacts]);

SectionList does not support numColumns, and it has no built-in section index (the A to Z strip on iOS); both need custom work or a library.

SectionList in a nutshell

sections Array of { title, data }.
Section header Receives your section object.
Sticky Default on iOS, off on Android.
1 / 2

Stand-in: grouped list with sticky headers

The component below groups names by their first letter and renders them in a scrolling box. It uses the CSS rule position: sticky to behave like a sticky section header. Scroll inside the box to see each letter stay pinned at the top.

Group a flat array into sections

Note that section.data.length in the header works because the header receives your own section object, just as in the real component.

Pull to refresh with RefreshControl

Pull to refresh is a controlled feature: you tell the list whether a refresh is in progress, and it shows the spinner while that is true. The shortcut is two props on the list itself:

TSX
const [refreshing, setRefreshing] = useState(false);

const onRefresh = useCallback(async () => {
  setRefreshing(true);
  try {
    const fresh = await fetchFeed();
    setItems(fresh);
  } finally {
    setRefreshing(false); // always, even when the request fails
  }
}, []);

<FlatList
  data={items}
  renderItem={renderItem}
  refreshing={refreshing}
  onRefresh={onRefresh}
/>

The finally is important. If the request throws and you never set refreshing back to false, the spinner hangs forever. For more control (colors, offsets) use the refreshControl prop with a RefreshControl element: <ScrollView refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}>. ScrollView, FlatList and SectionList all accept it.

Infinite scroll with onEndReached

onEndReached fires when the user scrolls within a certain distance of the end. onEndReachedThreshold sets that distance in units of the list's visible length: 0.5 means "when the end is half a screen away". Use it to fetch the next page:

TSX
<FlatList
  data={items}
  renderItem={renderItem}
  keyExtractor={keyOf}
  onEndReached={loadMore}
  onEndReachedThreshold={0.5}
  ListFooterComponent={loadingMore ? <ActivityIndicator /> : null}
/>

The catch is that onEndReached can fire more than once for the same end, especially while the new rows are still arriving or the content is short enough to be "at the end" right away. A correct loadMore therefore needs guards:

  1. Do nothing if a page is already loading.
  2. Do nothing if the server said there are no more pages.
  3. Do nothing during a refresh.
  4. On failure, show a retry instead of retrying in a loop.

Also keep in mind that after a refresh you replace the items with page 1, while loading more appends to them (with a new array, never a mutation). Track the page number or a cursor from the server, and when you merge, drop duplicates by id because new items can shift older ones onto the next page.

Stand-in: a paginated loader with guards

The stand-in below uses a fake fetchPage that answers after a short delay. A ref holds the "loading" flag so that repeated onEndReached calls in the same moment are ignored. The first button fires the event three times at once; the log shows only one request. The last button simulates pull to refresh, which starts over from page 1.

Paginated loader that ignores duplicate triggers

Press the first button once the first page has arrived: one request goes out, two calls are ignored. Press it again after page 3 and the list reports there are no more pages. Press "Pull to refresh" to see items replaced instead of appended. In a real app you would also keep an error state and a retry button, and cancel or ignore a response that arrives after a refresh (see Networking with fetch). Libraries such as TanStack Query give you useInfiniteQuery to manage this bookkeeping for you (see Server State with TanStack Query).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does renderSectionHeader receive?

    It gets { section }, the object from the sections array, so fields such as title or count are available.
  2. 2. A refresh fails with an error and the spinner never stops. What is the likely mistake?

    Set refreshing to false in a finally block so it happens on both success and failure.
  3. 3. Why can onEndReached run twice for the same end of the list?

    The event is not de-duplicated for you. Check a loading flag and a hasMore flag before requesting another page.
  4. 4. How do refresh and load-more differ when updating items?

    Refresh starts over from the first page. Load-more adds the next page, using a new array rather than mutating the old one.
  5. 5. What is the default for stickySectionHeadersEnabled?

    It differs by platform, so set it explicitly if you need identical behavior.

Summary

  • SectionList takes sections ({ title, data } objects), renderItem and renderSectionHeader; build the groups in useMemo from flat data.
  • Sticky headers are on by default only on iOS; give them an opaque background.
  • Pull to refresh is controlled: set refreshing to true while loading and always back to false in finally.
  • onEndReached with onEndReachedThreshold powers infinite scroll, but it can fire repeatedly: guard with loading and hasMore flags, show a footer spinner and a retry on error.
  • Refresh replaces items with page 1; load-more appends the next page to a new array and removes duplicates.

Next, learn how mobile apps move between screens in Navigation Concepts for Mobile.