Skip to main content

Lesson 9 of 10

Mini Project: Optimized List - Clean Architecture

Build an optimized 10,000-item list using FlashList, with vertical-slice architecture, a clean architecture use case for filtering, profiling before and after optimization, and a visible performance metrics overlay.

60 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

10,000-Item FlashList with Architecture

10,000-Item FlashList with Architecture
import { FlashList } from '@shopify/flash-list';
import { useState, useMemo, useCallback, useEffect } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

// ---- Domain ----
interface Product { id: string; name: string; category: string; price: number; rating: number; }

class FilterProductsUseCase {
  execute(products: Product[], query: string, category: string | null): Product[] {
    return products.filter(p => {
      const matchesQuery = query.length < 2 || p.name.toLowerCase().includes(query.toLowerCase());
      const matchesCategory = !category || p.category === category;
      return matchesQuery && matchesCategory;
    });
  }
}

// ---- Generate 10,000 products ----
const CATEGORIES = ['Electronics', 'Clothing', 'Books', 'Home', 'Sports'];
const ALL_PRODUCTS: Product[] = Array.from({ length: 10_000 }, (_, i) => ({
  id: String(i),
  name: `Product ${i + 1}`,
  category: CATEGORIES[i % CATEGORIES.length],
  price: Math.round((Math.random() * 990 + 10) * 100) / 100,
  rating: Math.round(Math.random() * 40 + 10) / 10,
}));

const ITEM_HEIGHT = 80;
const filterUseCase = new FilterProductsUseCase();

// ---- Memoized product row ----
const ProductRow = React.memo(({ item }: { item: Product }) => (
  <View style={s.row}>
    <View style={s.rowIcon}>
      <Text style={s.rowIconText}>{item.category[0]}</Text>
    </View>
    <View style={{ flex: 1 }}>
      <Text style={s.rowName} numberOfLines={1}>{item.name}</Text>
      <Text style={s.rowCategory}>{item.category}</Text>
    </View>
    <View style={{ alignItems: 'flex-end' }}>
      <Text style={s.rowPrice}>${item.price}</Text>
      <Text style={s.rowRating}>⭐ {item.rating}</Text>
    </View>
  </View>
));

// ---- Screen ----
export default function ProductListScreen() {
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState<string | null>(null);
  const [renderCount, setRenderCount] = useState(0);

  // Debounce query (300ms) - prevents filtering on every keystroke
  const [debouncedQuery, setDebouncedQuery] = useState('');
  useEffect(() => {
    const t = setTimeout(() => setDebouncedQuery(query), 300);
    return () => clearTimeout(t);
  }, [query]);

  // useMemo: only recalculate when deps change
  const filtered = useMemo(() => {
    const start = Date.now();
    const result = filterUseCase.execute(ALL_PRODUCTS, debouncedQuery, category);
    console.log(`Filter took ${Date.now() - start}ms → ${result.length} items`);
    return result;
  }, [debouncedQuery, category]);

  const renderItem = useCallback(({ item }: { item: Product }) => (
    <ProductRow item={item} />
  ), []);

  const keyExtractor = useCallback((item: Product) => item.id, []);

  return (
    <SafeAreaView style={s.screen} edges={['top']}>
      {/* Performance overlay */}
      <View style={s.perfBadge}>
        <Text style={s.perfText}>{filtered.length.toLocaleString()} items</Text>
      </View>

      {/* Search */}
      <View style={s.searchRow}>
        <TextInput
          value={query}
          onChangeText={setQuery}
          placeholder="Search products..."
          placeholderTextColor="#475569"
          style={s.searchInput}
          returnKeyType="search"
          clearButtonMode="while-editing"
        />
      </View>

      {/* Category filters */}
      <View style={s.filterRow}>
        {[null, ...CATEGORIES].map(cat => (
          <Pressable
            key={cat ?? 'all'}
            onPress={() => setCategory(cat)}
            style={[s.filterChip, category === cat && s.filterChipActive]}
          >
            <Text style={[s.filterChipText, category === cat && s.filterChipTextActive]}>
              {cat ?? 'All'}
            </Text>
          </Pressable>
        ))}
      </View>

      {/* Optimized list */}
      <FlashList
        data={filtered}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
        estimatedItemSize={ITEM_HEIGHT}
        drawDistance={ITEM_HEIGHT * 20}  // pre-render 20 items above and below viewport
        showsVerticalScrollIndicator={false}
        ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: '#1e293b', marginLeft: 72 }} />}
      />
    </SafeAreaView>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#0f172a' },
  perfBadge: { position: 'absolute', top: 12, right: 16, zIndex: 10, backgroundColor: '#229c6b', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 8 },
  perfText: { color: 'white', fontSize: 11, fontWeight: '700' },
  searchRow: { paddingHorizontal: 16, paddingTop: 60, paddingBottom: 8 },
  searchInput: { backgroundColor: '#1e293b', borderRadius: 10, padding: 12, fontSize: 15, color: '#f1f5f9', borderWidth: 1, borderColor: '#334155' },
  filterRow: { flexDirection: 'row', paddingHorizontal: 12, paddingBottom: 8, gap: 8 },
  filterChip: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 20, backgroundColor: '#1e293b' },
  filterChipActive: { backgroundColor: '#229c6b' },
  filterChipText: { color: '#64748b', fontSize: 12, fontWeight: '600' },
  filterChipTextActive: { color: 'white' },
  row: { height: ITEM_HEIGHT, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, gap: 12 },
  rowIcon: { width: 44, height: 44, borderRadius: 10, backgroundColor: '#1e293b', alignItems: 'center', justifyContent: 'center' },
  rowIconText: { fontSize: 20 },
  rowName: { fontSize: 14, fontWeight: '600', color: '#f1f5f9' },
  rowCategory: { fontSize: 12, color: '#64748b', marginTop: 2 },
  rowPrice: { fontSize: 14, fontWeight: '700', color: '#229c6b' },
  rowRating: { fontSize: 11, color: '#94a3b8', marginTop: 2 },
});

Tip

Tip

Practice Mini Project Optimized List Clean Architecture in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

10,000 item virtualized catalog maintaining smooth 120 FPS scrolling

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Optimized List Clean Architecture from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Optimized List Clean Architecture is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/10 done