CodeBlanks Logo Icon CodeBlanks

FlatList

Learn to render efficient lists with FlatList.

FlatList

FlatList is the component for efficiently showing long lists. It takes three core props: data for the array, renderItem for the function that draws each item, and keyExtractor to return a unique key for each item. It only renders the items that are visible; even thousands of items stay smooth.

Using FlatList instead of placing items one by one inside a ScrollView boosts performance. ScrollView renders all its children at once; FlatList renders only what is visible. That is why long lists always prefer FlatList.

Three core props

Writing a FlatList takes three props. data takes an array: data={numbers}. renderItem takes a function that draws each item: renderItem={({ item }) => <Text>{item}</Text>}. keyExtractor returns a unique key for each item.

Example: <FlatList data={[1, 2, 3]} renderItem={({ item }) => <Text>{item}</Text>} keyExtractor={(item) => item.toString()} />. These three props work together; missing one either breaks the list or raises a warning. The renderItem parameter is an object whose item property is the current array element.

Practice Write a number list

Complete the empty component. The numbers array is already defined: [1, 2, 3]. Return <FlatList data={numbers} renderItem={({ item }) => <Text>{item}</Text>} keyExtractor={(item) => item.toString()} />.

Starter code

App.js
import React from 'react';
import { FlatList, Text } from 'react-native';

export default function NumberList() {
  const numbers = [1, 2, 3];
  // Add a FlatList
  return null;
}

Sample solution

App.js
import React from 'react';
import { FlatList, Text } from 'react-native';

export default function NumberList() {
  const numbers = [1, 2, 3];
  return (
    <FlatList
      data={numbers}
      renderItem={({ item }) => <Text>{item}</Text>}
      keyExtractor={(item) => item.toString()}
    />
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is FlatList more efficient than ScrollView?

App.js
/* a list of 1000 items */
  • It draws all items at once
  • It accepts fewer props
  • It hides the items
  • It draws only the visible items Correct answer

Explanation: FlatList renders only the items visible on the screen.

2 Write the data prop

Question
<FlatList ____={numbers} renderItem={renderItem} keyExtractor={keyExtractor} />
Answer
<FlatList data={numbers} renderItem={renderItem} keyExtractor={keyExtractor} />

Explanation: The data prop takes the array to list.

3 Match each prop to its job

Term Meaning
data List array
renderItem Draws each item
keyExtractor Unique key
FlatList Efficient list component

All lessons in Beginner