Implementing List Refresh Control
In this lesson, you will learn how to enable users to update their list data by pulling down on the screen.
When displaying dynamic information—like a social media feed or a weather list—users expect a way to manually fetch the latest content. In React Native, the FlatList component has a built-in mechanism for this called RefreshControl.
Adding the Refresh Interaction
To implement this, you need two things: a piece of state to track if the list is currently loading, and the refreshControl prop passed into your FlatList.
First, import RefreshControl from react-native. Then, create a state variable (typically a boolean like isRefreshing) to signal when the fetch process is active.
import React, { useState } from 'react';
import { FlatList, RefreshControl, Text } from 'react-native';
const MyList = () => {
const [isRefreshing, setIsRefreshing] = useState(false);
const onRefresh = () => {
setIsRefreshing(true);
// Simulate a network request
setTimeout(() => {
setIsRefreshing(false);
}, 2000);
};
return (
<FlatList
data={myData}
renderItem={({ item }) => <Text>{item.title}</Text>}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={onRefresh}
/>
}
/>
);
};
How it Works
- The State: When the user pulls down, the
onRefreshfunction triggers. You immediately setisRefreshingtotrue. This tells theRefreshControlto display the native loading spinner. - The Logic: Inside
onRefresh, you would typically call your API or data-fetching logic. - The Reset: Once your data successfully updates, you set
isRefreshingback tofalse. This automatically hides the spinner and lets the user know the process is complete.
Because the RefreshControl is a sub-component of the FlatList, it understands exactly how much distance the user has pulled down before triggering your function, providing that smooth, native feel that users expect from mobile applications.
Key Takeaway: Use the refreshControl prop on your FlatList combined with a boolean state to toggle a native loading spinner while your data updates.