Mobile development · Intermediate · 22 min
Render long lists smoothly in React Native with FlashList
By Padding · Updated 18 Nov 2026
Expo SDK 58 · React Native 0.88 · FlashList 2.3.3 · Node.js 26 (node:26)
You will have a 2,000-row practitioner directory in an Expo SDK 58 app, built with FlashList 2.3, with sticky letter headers, pull to refresh, memoised rows and Jest tests that prove only the rows near the screen are mounted.
On this page
A directory of 2,000 people looks like a simple screen: a name, a job and a town on each line. Render it with ScrollView and map(), though, and React Native creates all 2,000 rows before the person sees the first one. Start-up stalls, memory climbs, and on a 2 or 3 GB Android phone the app can be killed in the background. The fix is a list that only keeps the rows near the screen alive.
You will build that directory in an Expo SDK 58 app with @shopify/flash-list 2.3. The rows are grouped under sticky letter headers, the list refreshes when pulled down, and each row is cheap enough to bind new data in a fraction of a frame. Jest tests prove the difference: the ScrollView version mounts 2,000 rows, the FlashList version a few dozen. You finish by measuring both on a phone.
Step 1 · Create the app and install FlashList
Create a throwaway app. When it asks to download create-expo-app, answer y:
cd ~
npx create-expo-app@5.0.0 flashlist-directory-demo
cd ~/flashlist-directory-demo
npx expo install @shopify/flash-listnpx expo install picks the FlashList version that SDK 58 was tested with. FlashList 2 is written entirely in JavaScript and runs only on React Native's New Architecture, which every SDK 58 app uses. Because it has no native code of its own, it works in Expo Go as well as in a development build.
Now add Jest, the Expo preset and React Native Testing Library:
cd ~/flashlist-directory-demo
npx expo install --dev jest-expo jest @types/jest
npm install --save-dev @testing-library/react-native@14.1.0 test-renderer@1.3.1FlashList measures its rows on screen, and there is no screen under Jest. The package ships a setup file that replaces those measurements with fixed sizes: a 400 by 900 point list and 100 point rows. FlashList is also published as modern JavaScript modules, which Jest only understands after Babel has transformed them, so it has to be added to the packages the Expo preset already transforms:
cd ~/flashlist-directory-demo
cat > jest.setup.js <<'JS'
// Gives FlashList fixed sizes under Jest: a 400 x 900 list and 100 x 100 rows.
require('@shopify/flash-list/jestSetup')
JS
cat > jest.config.js <<'JS'
module.exports = {
preset: 'jest-expo',
setupFiles: ['<rootDir>/jest.setup.js'],
// jest-expo's own list, plus @shopify/flash-list, which ships ES modules.
transformIgnorePatterns: [
'/node_modules/(?!(.pnpm|react-native|@react-native|@react-native-community|expo|@expo|@expo-google-fonts|react-navigation|@react-navigation|@sentry/react-native|native-base|standard-navigation|@shopify/flash-list))',
'/node_modules/react-native-reanimated/plugin/',
'/node_modules/@react-native/babel-preset/',
],
}
JS
npm pkg set scripts.test=jestCheck it worked
cd ~/flashlist-directory-demo
npm ls @shopify/flash-list
node -e "console.log(require('./jest.config.js').transformIgnorePatterns[0].includes('@shopify/flash-list'))"npm ls shows @shopify/flash-list@2.3.3 (or a later 2.3 patch), and the second command prints true.
Step 2 · Build 2,000 practitioners and their sections
Before any list code, write the data. A real app would load it from an API; here a small generator makes 2,000 practitioners with names from several languages, so you can see how sorting and grouping treat letters such as Ọ and É.
The list will be flat: one array holding both letter headers and people, with a type on each row. FlashList needs the header positions as numbers to make them sticky, so buildDirectory returns those too.
cd ~/flashlist-directory-demo
mkdir -p src/directory
cat > src/directory/practitioners.ts <<'TS'
export type Practitioner = {
id: string
name: string
role: string
town: string
photoUrl?: string
}
export type HeaderRow = { type: 'header'; key: string; letter: string; count: number }
export type PersonRow = { type: 'person'; key: string; practitioner: Practitioner }
export type DirectoryRow = HeaderRow | PersonRow
const GIVEN = [
'Adaeze', 'Kwame', 'Wanjiru', 'Thandiwe', 'Fatou', 'Oluwaseun', 'Chinedu', 'Zainab', 'Amara', 'Sipho',
'Nadia', 'Tomás', 'Mei', 'Priya', 'Yaw', 'Ngozi', 'Ọlá', 'Émile', 'Halima', 'Bongani',
]
const FAMILY = [
'Okonkwo', 'Mensah', 'Kamau', 'Dlamini', 'Diallo', 'Adeyemi', 'Eze', 'Bello', 'Nwosu', 'Ndlovu',
'Haddad', 'García', 'Chen', 'Patel', 'Boateng', 'Abubakar', 'Ògúnlẹ̀yẹ', 'Moreau', 'Tshabalala', 'Yusuf',
]
const ROLES = [
'General practitioner', 'Dentist', 'Physiotherapist', 'Pharmacist',
'Midwife', 'Optometrist', 'Dietitian', 'Nurse practitioner',
]
const TOWNS = ['Lagos', 'Accra', 'Nairobi', 'Kumasi', 'Durban', 'Dakar', 'Abuja', 'Kampala', 'Leeds', 'Toronto', 'Lyon', 'Cape Town']
// Deterministic stand-in data: the same count always gives the same people.
export function makePractitioners(count: number): Practitioner[] {
return Array.from({ length: count }, (_, i) => {
const given = GIVEN[i % GIVEN.length]
const family = FAMILY[(7 * (i % GIVEN.length) + Math.floor(i / GIVEN.length)) % FAMILY.length]
return {
id: `p-${String(i + 1).padStart(4, '0')}`,
name: `${given} ${family}`,
role: ROLES[(i * 3) % ROLES.length],
town: TOWNS[(i * 5) % TOWNS.length],
}
})
}
const collator = new Intl.Collator('en', { sensitivity: 'base' })
// "Ọlá" files under O and "Émile" under E: strip the accents, keep the base letter.
export function initialOf(name: string): string {
const first = name.normalize('NFD').replace(/[̀-ͯ]/g, '').charAt(0).toUpperCase()
return /^[A-Z]$/.test(first) ? first : '#'
}
export function buildDirectory(people: readonly Practitioner[]): {
rows: DirectoryRow[]
stickyHeaderIndices: number[]
} {
const sorted = [...people].sort((a, b) => collator.compare(a.name, b.name) || a.id.localeCompare(b.id))
const rows: DirectoryRow[] = []
const stickyHeaderIndices: number[] = []
let header: HeaderRow | undefined
for (const practitioner of sorted) {
const letter = initialOf(practitioner.name)
if (header?.letter !== letter) {
header = { type: 'header', key: `header-${letter}`, letter, count: 0 }
stickyHeaderIndices.push(rows.length)
rows.push(header)
}
header.count++
rows.push({ type: 'person', key: practitioner.id, practitioner })
}
return { rows, stickyHeaderIndices }
}
TSThree choices here pay off later:
- every row has a
keythat comes from the data (p-0042,header-K), never from its position, so FlashList can tell rows apart when the list changes. Intl.Collatorwithsensitivity: 'base'sortsỌlánext toOluwaseuninstead of afterZ, which a plain<comparison would do. Hermes, the JavaScript engine in Expo apps, supportsIntlon Android and iOS.- the grouping runs once, outside any component, so scrolling never repeats it.
Test it:
cd ~/flashlist-directory-demo
cat > src/directory/practitioners.test.ts <<'TS'
import { buildDirectory, initialOf, makePractitioners } from './practitioners'
test('makes the same 2,000 people every time, with unique IDs', () => {
const people = makePractitioners(2000)
expect(people).toHaveLength(2000)
expect(new Set(people.map((p) => p.id)).size).toBe(2000)
expect(makePractitioners(2000)).toEqual(people)
})
test('files accented names under their base letter', () => {
expect(initialOf('Ọlá Bello')).toBe('O')
expect(initialOf('Émile Chen')).toBe('E')
expect(initialOf('42 Clinic')).toBe('#')
})
test('puts a header before each letter and records where it is', () => {
const { rows, stickyHeaderIndices } = buildDirectory(makePractitioners(2000))
const headers = rows.filter((row) => row.type === 'header')
expect(stickyHeaderIndices[0]).toBe(0)
expect(stickyHeaderIndices).toHaveLength(headers.length)
expect(stickyHeaderIndices.every((i) => rows[i].type === 'header')).toBe(true)
expect(headers.map((h) => h.letter)).toEqual(['A', 'B', 'C', 'E', 'F', 'H', 'K', 'M', 'N', 'O', 'P', 'S', 'T', 'W', 'Y', 'Z'])
expect(headers.reduce((sum, h) => sum + h.count, 0)).toBe(2000)
expect(rows).toHaveLength(2016)
})
TS
npx jest src/directory/practitioners --ciCheck it worked
Jest reports Tests: 3 passed, 3 total. The directory has 16 letter headers and 2,016 rows in all.
Step 3 · See why ScrollView with map() falls over
Start with the version most people write first. It is worth seeing fail, because the failure is invisible with 20 rows and only shows at a few hundred.
cd ~/flashlist-directory-demo
cat > src/directory/naive-list.tsx <<'TSX'
import { ScrollView, Text, View } from 'react-native'
import type { Practitioner } from './practitioners'
// Do not ship this: every row is created up front, however long the list is.
export function NaiveList({ people }: { people: readonly Practitioner[] }) {
return (
<ScrollView>
{people.map((p) => (
<View key={p.id} testID="practitioner-row" style={{ height: 72, padding: 12 }}>
<Text>{p.name}</Text>
<Text>{p.role} · {p.town}</Text>
</View>
))}
</ScrollView>
)
}
TSX
cat > src/directory/naive-list.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { NaiveList } from './naive-list'
import { makePractitioners } from './practitioners'
test('a ScrollView mounts every row, even the ones far off screen', async () => {
await render(<NaiveList people={makePractitioners(2000)} />)
expect(screen.getAllByTestId('practitioner-row')).toHaveLength(2000)
}, 60_000)
TSX
npx jest src/directory/naive-list --ciEach of those 2,000 rows is three native views and two text nodes, created and laid out before the first frame, and kept in memory for as long as the screen is open. The person sees perhaps ten of them.
The two list components in common use avoid this in different ways:
- FlatList, built into React Native, virtualises. It renders a window of rows around the screen and unmounts rows that leave it. Scroll fast and it has to create new rows from nothing, and if it falls behind you see blank space.
- FlashList recycles. When a row scrolls off the top, FlashList keeps the component and its native views and hands them the data for the row coming on at the bottom. Binding new data to an existing row is much cheaper than building one.
Recycling has a consequence you design for: a row component is reused for different people. Anything it keeps in useState carries over to the next person unless you reset it. FlashList exports useRecyclingState for that case; the rows in this tutorial avoid local state altogether.
Check it worked
Jest reports Tests: 1 passed, 1 total, having found all 2,000 rows mounted. Note how long the test took in the Jest output; compare it with the FlashList test's time later in this tutorial, which renders the same data set.
Step 4 · Write a row that is cheap to recycle
FlashList calls your row component every time it binds a new person to a recycled row, so the row should do as little as possible: no data shaping, no state, no layout that changes after it appears.
cd ~/flashlist-directory-demo
cat > src/directory/practitioner-row.tsx <<'TSX'
import { Image } from 'expo-image'
import { memo } from 'react'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import type { Practitioner } from './practitioners'
const AVATAR = 48
type RowProps = {
practitioner: Practitioner
onSelect: (id: string) => void
}
function initials(name: string): string {
return name
.split(' ')
.map((part) => part.charAt(0))
.join('')
.slice(0, 2)
.toUpperCase()
}
function PractitionerRowBase({ practitioner, onSelect }: RowProps) {
const { id, name, role, town, photoUrl } = practitioner
return (
<Pressable
testID="practitioner-row"
accessibilityRole="button"
accessibilityLabel={`${name}, ${role}, ${town}`}
onPress={() => onSelect(id)}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
>
{photoUrl ? (
// Fixed size, so the row never changes height when the photo arrives.
// recyclingKey clears the previous person's photo when the row is reused.
<Image source={photoUrl} recyclingKey={id} style={styles.avatar} contentFit="cover" accessible={false} />
) : (
<View style={[styles.avatar, styles.initials]}>
<Text style={styles.initialsText}>{initials(name)}</Text>
</View>
)}
<View style={styles.text}>
<Text style={styles.name} numberOfLines={1}>{name}</Text>
<Text style={styles.detail} numberOfLines={1}>{role} · {town}</Text>
</View>
</Pressable>
)
}
// Re-renders only when this person or the onSelect function changes.
export const PractitionerRow = memo(PractitionerRowBase)
function SectionHeaderBase({ letter, count }: { letter: string; count: number }) {
return (
<View accessible accessibilityRole="header" accessibilityLabel={`${letter}, ${count} practitioners`} style={styles.header}>
<Text style={styles.headerLetter}>{letter}</Text>
<Text style={styles.headerCount}>{count}</Text>
</View>
)
}
export const SectionHeader = memo(SectionHeaderBase)
const styles = StyleSheet.create({
row: { flexDirection: 'row', alignItems: 'center', minHeight: 72, paddingHorizontal: 16, gap: 12, backgroundColor: '#ffffff' },
pressed: { backgroundColor: '#f1f2f4' },
avatar: { width: AVATAR, height: AVATAR, borderRadius: AVATAR / 2 },
initials: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#d9dce1' },
initialsText: { fontSize: 16, fontWeight: '600', color: '#2a2d33' },
text: { flex: 1 },
name: { fontSize: 16, fontWeight: '600', color: '#0b0c0e' },
detail: { fontSize: 14, color: '#6a707b' },
header: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 16, paddingVertical: 6, backgroundColor: '#f1f2f4' },
headerLetter: { fontSize: 14, fontWeight: '700', color: '#2a2d33' },
headerCount: { fontSize: 14, color: '#6a707b' },
})
TSXWhat makes this row cheap:
memo. When the screen re-renders, for example while the refresh spinner shows, React skips every row whose props are the same objects as last time. That only works if the parent passes the sameonSelectfunction on every render; the next step makes sure it does.- The inline
() => onSelect(id)is fine here. It is created inside the memoised row, so it only runs when the row itself renders. An inline function passed intoPractitionerRowfrom the list would be a new prop on every render and would switchmemooff. - No
keyprops inside the row. FlashList's documentation warns that keys inside an item stop it reusing the nested views. If a row ever has tomap()over child items, use FlashList'suseMappingHelperfor those keys. - Images sized up front. The avatar is always 48 by 48 points, photo or not, so a slow photo never pushes the text sideways or changes the row's height mid-scroll. On costly prepaid data, ask your server for a thumbnail near 96 or 144 pixels wide rather than the full photo.
numberOfLines={1}keeps every row the same height whatever the name's length, which is also kinder to long names in languages with diacritics stacked above and below.
Test what the person sees and does:
cd ~/flashlist-directory-demo
cat > src/directory/practitioner-row.test.tsx <<'TSX'
import { render, screen, userEvent } from '@testing-library/react-native'
import { PractitionerRow, SectionHeader } from './practitioner-row'
const adaeze = { id: 'p-0001', name: 'Adaeze Okonkwo', role: 'Dentist', town: 'Lagos' }
test('shows the name, role and town and reports the ID when pressed', async () => {
const onSelect = jest.fn()
const user = userEvent.setup()
await render(<PractitionerRow practitioner={adaeze} onSelect={onSelect} />)
expect(screen.getByText('Adaeze Okonkwo')).toBeOnTheScreen()
expect(screen.getByText('Dentist · Lagos')).toBeOnTheScreen()
expect(screen.getByText('AO')).toBeOnTheScreen()
await user.press(screen.getByRole('button', { name: 'Adaeze Okonkwo, Dentist, Lagos' }))
expect(onSelect).toHaveBeenCalledWith('p-0001')
})
test('shows a photo instead of initials when there is one', async () => {
await render(
<PractitionerRow practitioner={{ ...adaeze, photoUrl: 'https://example.com/thumbs/p-0001.jpg' }} onSelect={() => {}} />,
)
expect(screen.queryByText('AO')).toBeNull()
})
test('announces section headers as headings', async () => {
await render(<SectionHeader letter="K" count={125} />)
expect(screen.getByRole('header', { name: 'K, 125 practitioners' })).toBeOnTheScreen()
})
TSX
npx jest src/directory/practitioner-row --ciCheck it worked
Jest reports Tests: 3 passed, 3 total. The first test presses the row by the label a screen reader reads out, so a broken label fails the test as well as a broken handler.
Step 5 · Render the directory with FlashList
Now the list itself. Every function FlashList receives is either defined outside the component or wrapped in useCallback, so none of them changes between renders unless its inputs do.
cd ~/flashlist-directory-demo
cat > src/directory/directory-list.tsx <<'TSX'
import { FlashList, type ListRenderItem } from '@shopify/flash-list'
import { useCallback } from 'react'
import { PractitionerRow, SectionHeader } from './practitioner-row'
import type { DirectoryRow } from './practitioners'
type Props = {
rows: readonly DirectoryRow[]
stickyHeaderIndices: number[]
refreshing: boolean
onRefresh: () => void
onSelect: (id: string) => void
}
// Outside the component: the same function on every render.
const keyExtractor = (row: DirectoryRow) => row.key
// Headers and people get separate recycling pools, so a header is never rebuilt as a person.
const getItemType = (row: DirectoryRow) => row.type
export function DirectoryList({ rows, stickyHeaderIndices, refreshing, onRefresh, onSelect }: Props) {
const renderItem: ListRenderItem<DirectoryRow> = useCallback(
({ item }) =>
item.type === 'header' ? (
<SectionHeader letter={item.letter} count={item.count} />
) : (
<PractitionerRow practitioner={item.practitioner} onSelect={onSelect} />
),
[onSelect],
)
return (
<FlashList
testID="directory"
data={rows}
renderItem={renderItem}
keyExtractor={keyExtractor}
getItemType={getItemType}
stickyHeaderIndices={stickyHeaderIndices}
refreshing={refreshing}
onRefresh={onRefresh}
/>
)
}
TSXWhat each prop does:
keyExtractorgives FlashList a stable identity for each row. Without it, adding one person at the top looks like every row changed.getItemTypematters when rows differ in shape. FlashList keeps one pool of spare header rows and one of spare person rows, and takes from the matching pool. Keep it as fast as a property read: FlashList calls it constantly.stickyHeaderIndicespins the header for the section you are in to the top of the list until the next header pushes it away. The positions come frombuildDirectory, so they stay right when the data changes.refreshingandonRefreshadd the standard pull-to-refresh control. The next step wires them up.
FlashList 1 needed an estimatedItemSize. Version 2 measures rows itself, so leave it out. It also has a drawDistance prop, the distance beyond the screen it renders ahead (250 points by default on phones). Leave that alone unless you see blank rows during a fast fling on a real device; raising it trades memory for coverage.
Test that the list mounts only what is near the screen. Under Jest, the setup file makes the list 900 points tall and every row 100 points, so about a dozen rows fit:
cd ~/flashlist-directory-demo
cat > src/directory/directory-list.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { DirectoryList } from './directory-list'
import { buildDirectory, makePractitioners, type PersonRow } from './practitioners'
const { rows, stickyHeaderIndices } = buildDirectory(makePractitioners(2000))
function renderList() {
return render(
<DirectoryList
rows={rows}
stickyHeaderIndices={stickyHeaderIndices}
refreshing={false}
onRefresh={() => {}}
onSelect={() => {}}
/>,
)
}
test('mounts only the rows near the screen', async () => {
await renderList()
const mounted = await screen.findAllByTestId('practitioner-row')
expect(mounted.length).toBeGreaterThan(0)
expect(mounted.length).toBeLessThan(60)
const last = rows[rows.length - 1] as PersonRow
expect(screen.queryByText(last.practitioner.name)).toBeNull()
})
test('starts with the first section header and its people', async () => {
await renderList()
const first = rows[1] as PersonRow
expect((await screen.findAllByRole('header', { name: /^A, \d+ practitioners$/ })).length).toBeGreaterThan(0)
expect((await screen.findAllByText(first.practitioner.name)).length).toBeGreaterThan(0)
})
TSX
npx jest src/directory/directory-list --ciCheck it worked
Jest reports Tests: 2 passed, 2 total. The first test finds fewer than 60 rows mounted out of 2,000, and the last person in the directory is not rendered at all until someone scrolls to them.
Step 6 · Add pull to refresh and the screen
The screen owns the data. It starts from the list already on the phone, so the directory appears at once, and pulling down fetches a fresh copy. onSelect and onRefresh are wrapped in useCallback, so the memoised rows see the same function on every render, including the renders while the spinner shows.
The fetch below is a stand-in that waits briefly and returns one extra practitioner. In your app, replace its body with a call to your own API, with the address in an EXPO_PUBLIC_API_URL environment variable rather than written into the code.
cd ~/flashlist-directory-demo
cat > src/directory/api.ts <<'TS'
import { makePractitioners, type Practitioner } from './practitioners'
// Stand-in for your API. Replace the body with something like:
// const res = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/practitioners`)
// if (!res.ok) throw new Error(`HTTP ${res.status}`)
// return res.json()
export async function fetchPractitioners(): Promise<readonly Practitioner[]> {
await new Promise((resolve) => setTimeout(resolve, 600))
return makePractitioners(2001)
}
TS
cat > src/directory/directory-screen.tsx <<'TSX'
import { useCallback, useMemo, useState } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import { DirectoryList } from './directory-list'
import { buildDirectory, type Practitioner } from './practitioners'
type Props = {
initial: readonly Practitioner[]
load: () => Promise<readonly Practitioner[]>
}
export function DirectoryScreen({ initial, load }: Props) {
const [people, setPeople] = useState(initial)
const [refreshing, setRefreshing] = useState(false)
const [failed, setFailed] = useState(false)
const [selectedId, setSelectedId] = useState<string | null>(null)
// Sorting and grouping 2,000 people runs only when the people change.
const { rows, stickyHeaderIndices } = useMemo(() => buildDirectory(people), [people])
const onRefresh = useCallback(async () => {
setRefreshing(true)
setFailed(false)
try {
setPeople(await load())
} catch {
setFailed(true)
} finally {
setRefreshing(false)
}
}, [load])
const onSelect = useCallback((id: string) => setSelectedId(id), [])
const selected = selectedId ? people.find((p) => p.id === selectedId) : undefined
return (
<View style={styles.screen}>
<Text style={styles.summary} accessibilityLiveRegion="polite">
{people.length.toLocaleString('en')} practitioners
</Text>
{failed && <Text style={styles.summary}>Could not refresh. Pull down to try again.</Text>}
{selected && <Text style={styles.summary}>Selected: {selected.name}</Text>}
<View style={styles.list}>
<DirectoryList
rows={rows}
stickyHeaderIndices={stickyHeaderIndices}
refreshing={refreshing}
onRefresh={onRefresh}
onSelect={onSelect}
/>
</View>
</View>
)
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#ffffff' },
summary: { paddingHorizontal: 16, paddingVertical: 8, fontSize: 14, color: '#2a2d33' },
list: { flex: 1 },
})
TSX
cat > src/app/explore.tsx <<'TSX'
import { SafeAreaView } from 'react-native-safe-area-context'
import { fetchPractitioners } from '../directory/api'
import { DirectoryScreen } from '../directory/directory-screen'
import { makePractitioners } from '../directory/practitioners'
// In a real app this is the copy saved on the phone from the last refresh.
const initial = makePractitioners(2000)
export default function DirectoryTab() {
return (
<SafeAreaView style={{ flex: 1 }} edges={['top']}>
<DirectoryScreen initial={initial} load={fetchPractitioners} />
</SafeAreaView>
)
}
TSXThis replaces the template's Explore tab with the directory, so it opens from the second tab. FlashList needs a parent with a real height, which is why the list sits inside a View with flex: 1; in a parent that shrinks to fit its content, a virtualised list has nothing to measure against. A failed refresh keeps the list the person already had and says so in text, which matters on patchy mobile connections.
Test the refresh and the selection. The pull gesture itself needs a phone, so the test calls the refresh handler FlashList gave the scroll view, which is what the gesture does:
cd ~/flashlist-directory-demo
cat > src/directory/directory-screen.test.tsx <<'TSX'
import { act, render, screen, userEvent } from '@testing-library/react-native'
import { DirectoryScreen } from './directory-screen'
import { makePractitioners } from './practitioners'
function pullToRefresh() {
return act(async () => {
await screen.getByTestId('directory').props.refreshControl.props.onRefresh()
})
}
test('pull to refresh replaces the list with the new copy', async () => {
const load = jest.fn(async () => makePractitioners(2001))
await render(<DirectoryScreen initial={makePractitioners(2000)} load={load} />)
expect(screen.getByText('2,000 practitioners')).toBeOnTheScreen()
await pullToRefresh()
expect(await screen.findByText('2,001 practitioners')).toBeOnTheScreen()
expect(load).toHaveBeenCalledTimes(1)
})
test('a failed refresh keeps the old list and says so', async () => {
const load = jest.fn(async () => {
throw new Error('offline')
})
await render(<DirectoryScreen initial={makePractitioners(2000)} load={load} />)
await pullToRefresh()
expect(await screen.findByText('Could not refresh. Pull down to try again.')).toBeOnTheScreen()
expect(screen.getByText('2,000 practitioners')).toBeOnTheScreen()
})
test('pressing a row selects that practitioner', async () => {
const user = userEvent.setup()
await render(<DirectoryScreen initial={makePractitioners(2000)} load={async () => []} />)
const [firstRow] = await screen.findAllByTestId('practitioner-row')
await user.press(firstRow)
expect(await screen.findByText(/^Selected: /)).toBeOnTheScreen()
})
TSX
npx jest --ciCheck it worked
The full run reports five test suites and Tests: 12 passed, 12 total. If you remove useCallback from onSelect in directory-screen.tsx, the tests still pass, which is a reminder that tests prove behaviour, not speed. The next step shows how to see the cost.
Step 7 · Export the app and measure it on a phone
First confirm the production bundle builds and contains FlashList and your screen:
cd ~/flashlist-directory-demo
npx expo export --platform android
grep -a -c "FlashList v2 is only supported on new architecture" dist/_expo/static/js/android/*.hbc
grep -a -q "practitioners" dist/_expo/static/js/android/*.hbc && echo practitionersThe first grep prints 1 or more (a message from inside FlashList). The second prints practitioners only when that word, from the screen's summary line, is in the bundle; if it is missing, the command prints nothing and fails.
Now measure on a phone or emulator. Start the development server and open the app in Expo Go by scanning the QR code:
cd ~/flashlist-directory-demo
npx expo startOpen the Explore tab, then the developer menu (shake the phone, or press m in the terminal), and turn on the performance monitor. It shows two frame rates:
- UI: the native thread that draws and scrolls. With FlashList it should stay close to the phone's refresh rate during a fast fling.
- JS: the JavaScript thread that renders rows. A recycling list keeps it busy only while rows are rebound, so dips should be brief.
For comparison, temporarily change src/app/explore.tsx to render <NaiveList people={initial} /> (imported from ../directory/naive-list) and reload. Expect the tab to take noticeably longer to appear, and the JS rate to drop while all 2,000 rows are created. Put the FlashList screen back when you are done.
To see which components render, press j in the npx expo start terminal to open React Native DevTools, go to the Profiler tab, record while you pull to refresh, and stop. The recording holds at least two commits. Select the one made as the spinner appears (the refreshing change): with useCallback in place, the screen and list render but the person rows do not. The last commit, made when the fresh list arrives, does re-render every visible row, because load() returns new practitioner objects and buildDirectory makes new rows from them. That is expected: the data really changed. Now remove useCallback from onSelect, record again and select the same spinner commit. This time every visible row appears in it: that is memo being defeated by a new function on each render.
Development mode adds checks that slow JavaScript down, so treat these numbers as a before-and-after comparison, not as what people will feel. For real figures, build a release version and test it on the cheapest phone you can get, ideally a 2 or 3 GB Android phone like many of your users carry:
npx expo run:android --variant releaseCheck it worked
The export finishes with the bundle in dist, and both grep commands print what is described above. On the phone, the directory opens on the Explore tab, the letter header stays pinned as you scroll through its section, pulling down shows the spinner and then 2,001 practitioners, and the performance monitor's UI rate stays near the top of its range during a fast scroll.
Next steps
- Find what else slows a React Native app on cheap phones in speeding up a React Native app on a low-end Android phone.
- Design screens that stay usable on small, slow devices with designing for low-end Android phones.
- If you are new to Expo, start with creating your first Expo app.
- To delete the demo, remove the folder:
rm -rf ~/flashlist-directory-demo.
Related tutorials
- How to Create Your First React Native App with ExpoYou will create an Expo SDK 58 project with TypeScript, look at what the template gives you, run it on your phone or in a simulator, replace the home screen with a small counter of your own, and check from the command line that the project bundles and passes expo-doctor.
- Speed up a React Native app on a low-end Android phoneYou will measure a release build of your Expo app on a 2 to 3 GB Android phone, fix slow startup, dropped frames and re-render storms, and finish with a written performance budget you can check before every release.
- Design for low-end Android phonesYou will have a written low-end phone profile, a Larkfield Clinic booking screen revised to work at 360 by 640 dp on a dim screen with large text, and a constraint checklist your team can run on every new screen.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials