0
0
React Nativemobile~5 mins

Pull-to-refresh in React Native

Choose your learning style9 modes available
Introduction

Pull-to-refresh lets users update content by pulling down on the screen. It feels natural and easy, like flipping a page to see new stuff.

Refreshing a list of messages in a chat app.
Updating news headlines in a news app.
Reloading a feed of photos or posts in a social media app.
Refreshing weather information on a weather app.
Syntax
React Native
import { RefreshControl, ScrollView } from 'react-native';

<ScrollView
  refreshControl={
    <RefreshControl
      refreshing={refreshing}
      onRefresh={onRefresh}
    />
  }
>
  {/* Your scrollable content here */}
</ScrollView>

refreshing is a boolean state that shows if the refresh is happening.

onRefresh is a function called when the user pulls down to refresh.

Examples
This example shows how to control the refreshing state and simulate data fetching.
React Native
const [refreshing, setRefreshing] = useState(false);

const onRefresh = () => {
  setRefreshing(true);
  // fetch new data here
  setTimeout(() => setRefreshing(false), 2000);
};
Basic ScrollView with pull-to-refresh enabled.
React Native
<ScrollView
  refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
>
  <Text>Pull down to refresh</Text>
</ScrollView>
Sample App

This app shows a list of fruits. When you pull down, it adds a new fruit after a short delay, showing the refresh effect.

React Native
import React, { useState, useCallback } from 'react';
import { View, Text, ScrollView, RefreshControl, StyleSheet } from 'react-native';

export default function PullToRefreshExample() {
  const [refreshing, setRefreshing] = useState(false);
  const [items, setItems] = useState(['Apple', 'Banana', 'Cherry']);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    setTimeout(() => {
      setItems(prevItems => [...prevItems, 'New Fruit']);
      setRefreshing(false);
    }, 1500);
  }, []);

  return (
    <ScrollView
      contentContainerStyle={styles.container}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
    >
      {items.map((item, index) => (
        <Text key={index} style={styles.item}>{item}</Text>
      ))}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20 },
  item: { fontSize: 18, marginVertical: 8 }
});
OutputSuccess
Important Notes

Always set refreshing to false after your data loads to stop the spinner.

Use useCallback for onRefresh to avoid unnecessary re-renders.

Pull-to-refresh works only inside scrollable views like ScrollView or FlatList.

Summary

Pull-to-refresh lets users update content by pulling down on a list.

Use RefreshControl inside a scrollable component with refreshing and onRefresh props.

Remember to update the refreshing state to show and hide the loading spinner.