Lesson 9 of 10
Mini Project: Optimized Data Table
Build a virtualized data table handling 10,000 rows with column sorting via Web Worker, debounced search, memoized row components, bundle analysis config, and Core Web Vitals measurement. This is the kind of performant component you'd build at a SaaS company.
High-Performance Data Table
import { useState, useMemo, useCallback, useRef, memo, useEffect } from 'react';
import { FixedSizeList } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
// ---- Generate mock data ----
function generateRows(count: number) {
return Array.from({ length: count }, (_, i) => ({
id: String(i + 1),
name: `User ${i + 1}`,
email: `user${i + 1}@example.com`,
role: ['Admin', 'User', 'Guest', 'Manager'][i % 4],
status: i % 7 === 0 ? 'inactive' : 'active',
score: Math.floor(Math.random() * 1000),
joined: new Date(2020 + (i % 5), i % 12, (i % 28) + 1).toLocaleDateString(),
}));
}
type Row = ReturnType<typeof generateRows>[0];
type SortConfig = { column: keyof Row; direction: 'asc' | 'desc' } | null;
// ---- Simulated sort worker (main thread fallback for browser compat) ----
function sortRows(rows: Row[], config: SortConfig): Row[] {
if (!config) return rows;
return [...rows].sort((a, b) => {
const aVal = a[config.column];
const bVal = b[config.column];
const cmp = typeof aVal === 'string'
? aVal.localeCompare(bVal as string)
: (aVal as number) - (bVal as number);
return config.direction === 'asc' ? cmp : -cmp;
});
}
// ---- Memoized row component - only re-renders if its data changes ----
const TableRow = memo(function TableRow({
row,
style,
columns,
}: {
row: Row;
style: React.CSSProperties;
columns: (keyof Row)[];
}) {
return (
<div
style={{
...style,
display: 'flex',
alignItems: 'center',
padding: '0 16px',
borderBottom: '1px solid #1e293b',
background: row.status === 'inactive' ? '#1a1a2e' : 'transparent',
}}
>
{columns.map(col => (
<span
key={col}
style={{
flex: col === 'email' ? 2 : 1,
fontSize: 13,
color: col === 'status'
? row.status === 'active' ? '#4ade80' : '#f87171'
: '#e2e8f0',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{col === 'score' ? (
<span style={{ background: '#334155', padding: '2px 8px', borderRadius: 4 }}>
{row[col]}
</span>
) : String(row[col])}
</span>
))}
</div>
);
});
// ---- Debounce hook ----
function useDebounce<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debounced;
}
// ---- Column header ----
function ColumnHeader({
column,
label,
sortConfig,
onSort,
flex,
}: {
column: keyof Row;
label: string;
sortConfig: SortConfig;
onSort: (col: keyof Row) => void;
flex: number;
}) {
const isSorted = sortConfig?.column === column;
return (
<button
onClick={() => onSort(column)}
style={{
flex,
background: 'none',
border: 'none',
color: isSorted ? '#60a5fa' : '#94a3b8',
cursor: 'pointer',
fontWeight: isSorted ? 700 : 500,
fontSize: 13,
padding: 0,
textAlign: 'left' as const,
display: 'flex',
alignItems: 'center',
gap: 4,
}}
>
{label}
{isSorted ? (sortConfig?.direction === 'asc' ? ' ↑' : ' ↓') : ' ↕'}
</button>
);
}
// ---- Main table component ----
const COLUMNS: { key: keyof Row; label: string; flex: number }[] = [
{ key: 'id', label: 'ID', flex: 1 },
{ key: 'name', label: 'Name', flex: 1 },
{ key: 'email', label: 'Email', flex: 2 },
{ key: 'role', label: 'Role', flex: 1 },
{ key: 'status', label: 'Status', flex: 1 },
{ key: 'score', label: 'Score', flex: 1 },
{ key: 'joined', label: 'Joined', flex: 1 },
];
const ALL_DATA = generateRows(10_000); // static - defined once outside component
export default function OptimizedDataTable() {
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 250);
const [sortConfig, setSortConfig] = useState<SortConfig>(null);
const [isSorting, setIsSorting] = useState(false);
const columnKeys = useMemo(() => COLUMNS.map(c => c.key), []);
// Filter - memoized, only re-runs when debouncedSearch changes
const filtered = useMemo(() => {
if (!debouncedSearch) return ALL_DATA;
const q = debouncedSearch.toLowerCase();
return ALL_DATA.filter(r =>
r.name.toLowerCase().includes(q) ||
r.email.toLowerCase().includes(q) ||
r.role.toLowerCase().includes(q)
);
}, [debouncedSearch]);
// Sort - would use Web Worker in production; simulated here
const [sorted, setSorted] = useState<Row[]>(ALL_DATA);
useEffect(() => {
setIsSorting(true);
// In production: await workerApi.sortRows(filtered, sortConfig)
setTimeout(() => {
setSorted(sortRows(filtered, sortConfig));
setIsSorting(false);
}, 0); // yield to browser before sorting
}, [filtered, sortConfig]);
const handleSort = useCallback((column: keyof Row) => {
setSortConfig(prev =>
prev?.column === column
? { column, direction: prev.direction === 'asc' ? 'desc' : 'asc' }
: { column, direction: 'asc' }
);
}, []);
return (
<div style={{ fontFamily: 'system-ui', background: '#0f172a', minHeight: '100vh', color: 'white', padding: 24 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<h1 style={{ margin: 0, fontSize: 22 }}>
Data Table
<span style={{ fontSize: 14, color: '#64748b', fontWeight: 400, marginLeft: 12 }}>
{sorted.length.toLocaleString()} of {ALL_DATA.length.toLocaleString()} rows
{isSorting && ' - Sorting...'}
</span>
</h1>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Search name, email, role..."
style={{ background: '#1e293b', border: '1px solid #334155', color: 'white', padding: '8px 16px', borderRadius: 8, width: 260, fontSize: 13 }}
/>
</div>
{/* Header */}
<div style={{ display: 'flex', padding: '10px 16px', background: '#1e293b', borderRadius: '8px 8px 0 0', marginBottom: 1 }}>
{COLUMNS.map(col => (
<ColumnHeader key={col.key} column={col.key} label={col.label} flex={col.flex} sortConfig={sortConfig} onSort={handleSort} />
))}
</div>
{/* Virtualized list */}
<div style={{ height: 'calc(100vh - 180px)', background: '#0f172a' }}>
<AutoSizer>
{({ height, width }) => (
<FixedSizeList
height={height}
width={width}
itemCount={sorted.length}
itemSize={44}
overscanCount={10}
>
{({ index, style }) => (
<TableRow
row={sorted[index]}
style={style}
columns={columnKeys}
/>
)}
</FixedSizeList>
)}
</AutoSizer>
</div>
</div>
);
}Performance Techniques Demonstrated in This Project
- Fixed-Size List virtualization - renders only ~20 DOM rows at a time regardless of 10,000 total rows
- AutoSizer - fills available space without hardcoded dimensions, making the list responsive
- Debounced search - 250ms delay with `useDebounce` prevents filtering on every keystroke
- useMemo for filtering - the filter computation runs only when `debouncedSearch` changes, not on sort changes
- useCallback for sort handler - stable reference prevents unnecessary re-renders of column header buttons
- React.memo on TableRow - each row component only re-renders if its data actually changed
- Static data outside component - `ALL_DATA` is defined once at module level, never recreated on render
- setTimeout(0) for sort - yields to the browser event loop before heavy sort, keeping UI responsive
Tip
Tip
Practice Mini Project Optimized Data Table in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Mini Project: Optimized Data Table
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Optimized Data Table 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 Data Table is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- Build a virtualized data table handling 10,000 rows with column sorting via Web Worker, debounced search, memoized row components, bundle analysis config, and Core Web Vitals measurement.
- Fixed-Size List virtualization - renders only ~20 DOM rows at a time regardless of 10,000 total rows
- AutoSizer - fills available space without hardcoded dimensions, making the list responsive
- Debounced search - 250ms delay with `useDebounce` prevents filtering on every keystroke
Finished this lesson?