Lesson 70 of 60 – Typing FlatList Data
100%

Typing FlatList Data

FlatList is one of the most commonly used React Native components for displaying lists of data. When working with TypeScript, we can define the type of each item in the list and make our FlatList code safer and easier to understand.

Note: The most important TypeScript concept when using FlatList is defining the type of each list item and passing that type to FlatList<T>.

1. What is FlatList?

FlatList is a React Native component used to efficiently display a list of items.

import { FlatList } from "react-native";

It is useful when an application needs to display many records such as students, products, users, messages, or posts.

2. Why Type FlatList Data?

Without proper types, it can be difficult to know which properties are available on each list item.

TypeScript allows us to define the exact structure of every item.

interface Student {
    id: number;
    name: string;
    course: string;
}

3. Creating Student Data

const students: Student[] = [
    {
        id: 1,
        name: "Rahul",
        course: "React Native"
    },
    {
        id: 2,
        name: "Priya",
        course: "TypeScript"
    }
];

The Student[] type means every item must follow the Student interface.

4. Basic Typed FlatList

<FlatList<Student>
    data={students}
    renderItem={({ item }) => (
        <Text>{item.name}</Text>
    )}
/>

FlatList<Student> tells TypeScript that every item in the list is a Student.

5. Understanding the Generic Type

The syntax below uses a generic type:

FlatList<Student>

Here, Student represents the type of one item in the list.

This allows TypeScript to understand the structure of item inside renderItem.

6. Typing renderItem

The renderItem callback receives information about the current item.

renderItem={({ item }) => (
    <Text>{item.name}</Text>
)}

Because FlatList is typed as Student, TypeScript knows that item is a Student.

7. Accessing Typed Properties

<Text>
    {item.name}
</Text>

<Text>
    {item.course}
</Text>

TypeScript provides information about the properties available on item.

8. keyExtractor

keyExtractor provides a unique key for each list item.

keyExtractor={(item) =>
    item.id.toString()
}

If id is a number, converting it to a string is a common approach for the key.

9. Typing keyExtractor

keyExtractor={(item: Student) =>
    item.id.toString()
}

The explicit type is usually not necessary when FlatList is already correctly typed, but it can make the expected item type clearer.

10. FlatList with React Native Text

import {
    FlatList,
    Text
} from "react-native";

interface Student {
    id: number;
    name: string;
}

const students: Student[] = [
    {
        id: 1,
        name: "Rahul"
    },
    {
        id: 2,
        name: "Priya"
    }
];

<FlatList<Student>
    data={students}
    keyExtractor={(item) =>
        item.id.toString()
    }
    renderItem={({ item }) => (
        <Text>{item.name}</Text>
    )}
/>

11. FlatList with Objects

A list item can contain several properties.

interface Product {
    id: number;
    name: string;
    price: number;
}

const products: Product[] = [
    {
        id: 1,
        name: "Keyboard",
        price: 800
    },
    {
        id: 2,
        name: "Mouse",
        price: 500
    }
];

12. Displaying Multiple Properties

<FlatList<Product>
    data={products}
    renderItem={({ item }) => (
        <View>

            <Text>
                {item.name}
            </Text>

            <Text>
                ₹{item.price}
            </Text>

        </View>
    )}
/>

TypeScript knows that item.name is a string and item.price is a number.

13. FlatList with useState

const [students, setStudents] =
    useState<Student[]>([]);

This is useful when list data changes during application execution.

<FlatList<Student>
    data={students}
    renderItem={({ item }) => (
        <Text>{item.name}</Text>
    )}
/>

14. Adding Items to a Typed List

setStudents(prev => [
    ...prev,
    {
        id: 3,
        name: "Amit",
        course: "JavaScript"
    }
]);

TypeScript checks that the new object follows the Student structure.

15. Removing Items

setStudents(prev =>
    prev.filter(student =>
        student.id !== 2
    )
);

The filtered result remains a Student[].

16. FlatList with API Data

FlatList is commonly used to display data received from an API.

const [students, setStudents] =
    useState<Student[]>([]);

const response =
    await fetch(url);

const data: Student[] =
    await response.json();

setStudents(data);

17. FlatList with Loading State

if (loading) {
    return (
        <ActivityIndicator />
    );
}

return (
    <FlatList<Student>
        data={students}
        renderItem={({ item }) => (
            <Text>{item.name}</Text>
        )}
    />
);

A loading indicator can be displayed while data is being requested.

18. FlatList with Empty Data

ListEmptyComponent can display a message when the list contains no data.

<FlatList<Student>
    data={students}
    renderItem={({ item }) => (
        <Text>{item.name}</Text>
    )}
    ListEmptyComponent={
        <Text>No students found.</Text>
    }
/>

19. FlatList with Pressable Items

renderItem={({ item }) => (
    <Pressable
        onPress={() =>
            console.log(item.id)
        }
    >

        <Text>
            {item.name}
        </Text>

    </Pressable>
)}

The typed item can be used safely inside the press handler.

20. Creating a Reusable List Item

interface StudentItemProps {
    student: Student;
}

function StudentItem(
    { student }: StudentItemProps
): React.JSX.Element {

    return (
        <View>
            <Text>
                {student.name}
            </Text>
        </View>
    );
}

A separate component can make large FlatList implementations easier to maintain.

21. Using a Reusable Item in FlatList

<FlatList<Student>
    data={students}
    keyExtractor={(item) =>
        item.id.toString()
    }
    renderItem={({ item }) => (
        <StudentItem
            student={item}
        />
    )}
/>

22. Optional Properties in List Items

interface Student {
    id: number;
    name: string;
    course?: string;
}

If course is optional, handle it safely when displaying it.

<Text>
    {item.course ?? "Course not available"}
</Text>

23. Common FlatList TypeScript Mistakes

  • Using any for all list data.
  • Forgetting to define an interface for complex items.
  • Using incorrect property names.
  • Using a number directly as a key without converting it to a string.
  • Adding objects that do not match the item interface.
  • Ignoring optional properties.
  • Not typing API response data.

24. Best Practices

  • Create an interface for important list item structures.
  • Use FlatList<YourType>.
  • Use a unique and stable identifier for keyExtractor.
  • Keep list item components small and reusable.
  • Type API data before placing it into state.
  • Handle loading, error, and empty states.
  • Avoid unnecessary use of any.

25. FlatList with Function Props

A reusable list item can receive a typed function to handle selection.

interface StudentItemProps {
    student: Student;
    onSelect: (student: Student) => void;
}

This ensures that the function receives a Student object.

26. Typed Item Selection

const handleStudent =
    (student: Student): void => {

    console.log(student.id);
    console.log(student.name);

};

The function can then be passed to a reusable list item.

27. FlatList with Refreshing

A typed FlatList can also be used with a refresh state.

const [refreshing, setRefreshing] =
    useState<boolean>(false);

<FlatList<Student>
    data={students}
    refreshing={refreshing}
    onRefresh={loadStudents}
    renderItem={({ item }) => (
        <Text>{item.name}</Text>
    )}
/>

28. Complete Typed FlatList Example

import React, {
    useState
} from "react";

import {
    View,
    Text,
    FlatList,
    Pressable,
    StyleSheet
} from "react-native";

interface Student {
    id: number;
    name: string;
    course: string;
}

const students: Student[] = [
    {
        id: 1,
        name: "Rahul",
        course: "React Native"
    },
    {
        id: 2,
        name: "Priya",
        course: "TypeScript"
    },
    {
        id: 3,
        name: "Amit",
        course: "JavaScript"
    }
];

export default function App(): React.JSX.Element {

    const [selectedId, setSelectedId] =
        useState<number | null>(null);

    const handleSelect =
        (student: Student): void => {

        setSelectedId(student.id);

    };

    return (
        <View style={styles.container}>

            <Text style={styles.title}>
                Student List
            </Text>

            <FlatList<Student>
                data={students}

                keyExtractor={(item) =>
                    item.id.toString()
                }

                renderItem={({ item }) => (

                    <Pressable
                        style={styles.item}
                        onPress={() =>
                            handleSelect(item)
                        }
                    >

                        <Text style={styles.name}>
                            {item.name}
                        </Text>

                        <Text>
                            {item.course}
                        </Text>

                        {selectedId === item.id && (

                            <Text>
                                Selected
                            </Text>

                        )}

                    </Pressable>

                )}
            />

        </View>
    );
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        padding: 20
    },

    title: {
        fontSize: 24,
        fontWeight: "bold",
        marginBottom: 15
    },

    item: {
        padding: 15,
        marginBottom: 10,
        borderWidth: 1,
        borderRadius: 8
    },

    name: {
        fontSize: 18,
        fontWeight: "bold"
    }

});

29. Why Typed FlatList is Useful

TypeScript makes FlatList code easier to understand and maintain. When the list is typed, the editor can provide suggestions and detect many incorrect property accesses during development.

  • Safer list item access
  • Better code completion
  • Clear data structures
  • Safer API integration
  • Better reusable components
  • Easier maintenance

30. Summary

FlatList is an important React Native component for displaying lists. TypeScript allows us to define the structure of each list item and pass that type to FlatList.

You should now understand interfaces for list data, typed FlatList, renderItem, keyExtractor, API data, useState, reusable list items, optional properties, selection, refreshing, and common TypeScript practices for FlatList.

📌 Key Points

  • Define an interface for complex FlatList items.
  • Use FlatList<Student> to type list items.
  • Type your list state with useState<Student[]>.
  • Use a unique identifier with keyExtractor.
  • Typed API data can be directly used with FlatList.
  • Reusable list components can receive typed item props.
  • Handle loading, error, empty, and refreshing states.
  • Avoid using any when a proper type can be defined.

🧠 Quick Quiz

Question: Which syntax correctly tells TypeScript that a FlatList contains Student objects?