-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptimizing-list-rendering.js
More file actions
72 lines (64 loc) · 1.91 KB
/
optimizing-list-rendering.js
File metadata and controls
72 lines (64 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 🧠 Concept: Optimizing List Rendering in React
*
* ------------------------------------------------------------
* 🧾 Why?
* - Rendering long lists can slow down performance.
* - Each re-render recalculates the full list, even for small changes.
* - Bad `key` usage or unnecessary renders cause jank and poor UX.
*
* ✅ Solution: Use best practices like proper `key`, `React.memo`, conditional rendering, pagination, and virtualization.
*/
import React, { memo, useMemo } from "react";
/**
* 🛠 OptimizedListItem Component
*
* - `memo` prevents unnecessary re-renders.
* - Only re-renders when props change.
*/
const OptimizedListItem = memo(({ item }) => {
console.log("Rendering:", item.name); // Debug: see which items re-render
return <li>{item.name}</li>;
});
/**
* 🧪 Example: A component using list rendering optimizations
*/
function OptimizedList({ items }) {
// Simulate expensive sorting/filtering logic only once using useMemo
const sortedItems = useMemo(() => {
return [...items].sort((a, b) => a.name.localeCompare(b.name));
}, [items]);
return (
<div style={{ padding: "1rem", fontFamily: "sans-serif" }}>
<h2>📋 Optimized List</h2>
<ul>
{sortedItems.map((item) => (
<OptimizedListItem key={item.id} item={item} />
))}
</ul>
</div>
);
}
/**
* 🧪 Example Usage
*/
function App() {
const sampleData = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Charlie" },
{ id: 3, name: "Bob" }
];
return <OptimizedList items={sampleData} />;
}
/**
* 🧵 Summary:
*
* ✅ Tips for Optimizing List Rendering:
* - Use `key` prop correctly (unique + stable).
* - Wrap list items with `React.memo`.
* - Use `useMemo` for expensive calculations.
* - Paginate or virtualize large lists.
*
* 🧩 Tip: Libraries like `react-window` or `react-virtualized` help with large lists.
*/
export { OptimizedList, App };