FlatList Avanzado
Volver a clases
Principiante

FlatList Avanzado

60 min
70 vistas

FlatList

Infinite Scroll

typescript
1function InfiniteList() {
2  const [data, setData] = useState<Product[]>([]);
3  const [page, setPage] = useState(1);
4  const [loading, setLoading] = useState(false);
5  const [hasMore, setHasMore] = useState(true);
6
7  const loadMore = async () => {
8    if (loading || !hasMore) return;
9
10    setLoading(true);
11
12    // Simular API call
13    const newData = await fetchProducts(page);
14
15    if (newData.length === 0) {
16      setHasMore(false);
17    } else {
18      setData([...data, ...newData]);
19      setPage(page + 1);
20    }
21
22    setLoading(false);
23  };
24
25  const renderFooter = () => {
26    if (!loading) return null;
27
28    return (
29      <View style={styles.footer}>
30        <ActivityIndicator size="large" color="#007AFF" />
31      </View>
32    );
33  };
34
35  return (
36    <FlatList
37      data={data}
38      renderItem={renderProduct}
39      keyExtractor={(item) => item.id.toString()}
40      onEndReached={loadMore}
41      onEndReachedThreshold={0.5}
42      ListFooterComponent={renderFooter}
43    />
44  );
45}

Listas Horizontales

typescript
1function HorizontalList() {
2  return (
3    <View>
4      <Text style={styles.sectionTitle}>Categorías</Text>
5      <FlatList
6        data={categories}
7        renderItem={({ item }) => (
8          <TouchableOpacity style={styles.categoryCard}>
9            <Text>{item.name}</Text>
10          </TouchableOpacity>
11        )}
12        keyExtractor={(item) => item.id.toString()}
13        horizontal
14        showsHorizontalScrollIndicator={false}
15        contentContainerStyle={styles.horizontalList}
16      />
17    </View>
18  );
19}
20
21const styles = StyleSheet.create({
22  horizontalList: {
23    paddingHorizontal: 16,
24    gap: 12,
25  },
26  categoryCard: {
27    width: 100,
28    height: 100,
29    backgroundColor: "#007AFF",
30    borderRadius: 12,
31    justifyContent: "center",
32    alignItems: "center",
33  },
34});

Optimización de Rendimiento

typescript
1import { memo } from "react";
2
3// Memoizar componentes de items
4const ProductItem = memo(({ item }: { item: Product }) => {
5  return (
6    <View style={styles.item}>
7      <Text>{item.name}</Text>
8      <Text>${item.price}</Text>
9    </View>
10  );
11});
12
13function OptimizedList() {
14  return (
15    <FlatList
16      data={products}
17      renderItem={({ item }) => <ProductItem item={item} />}
18      keyExtractor={(item) => item.id.toString()}
19      // Optimizaciones
20      removeClippedSubviews={true}
21      maxToRenderPerBatch={10}
22      updateCellsBatchingPeriod={50}
23      initialNumToRender={10}
24      windowSize={10}
25      // Altura fija mejora rendimiento
26      getItemLayout={(data, index) => ({
27        length: ITEM_HEIGHT,
28        offset: ITEM_HEIGHT * index,
29        index,
30      })}
31    />
32  );
33}