How to implement pull to refresh FlatList with React Native?

Sometimes, we want to implement pull to refresh FlatList with React Native.

In this article, we’ll look at how to implement pull to refresh FlatList with React Native.

How to implement pull to refresh FlatList with React Native?

To implement pull to refresh FlatList with React Native, we can set the refreshing and onRefresh props.

For instance, we write:

import * as React from 'react';
import { FlatList, Text, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const flatListItems = Array(200)
  .fill()
  .map((_, i) => ({ title: i, id: i }));

const Item = ({ title }) => (
  <View
    style={{
      backgroundColor: '#f9c2ff',
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
    }}>
    <Text>{title}</Text>
  </View>
);

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export default function App() {
  const [isFetching, setIsFetching] = React.useState(false);
  const renderItem = ({ item }) => <Item title={item.title} />;

  const onRefresh = async () => {
    setIsFetching(true);
    await sleep(2000);
    setIsFetching(false);
  };

  return (
    <View>
      <FlatList
        data={flatListItems}
        onRefresh={onRefresh}
        refreshing={isFetching}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}

to set the refreshing prop to isFetching, which is true when we’re getting data for the FlatList.

And we set onRefresh to the onRefresh which sets refreshing to true and then set it back to false after 2 seconds.

Conclusion

To implement pull to refresh FlatList with React Native, we can set the refreshing and onRefresh props.