| React-memo-vs-useMemo-vs-useCallback :👈 | 👉:Implement Virtualization for Long Lists |
How to Optimize a Large React List |
How to Optimize a Large React List
1. Introduction
Consider an application that displays 10,000 employee records in a React component. A simple implementation might look like this:
function EmployeeList({ employees }) {
return (
<div>
{employees.map(employee => (
<div key={employee.id}>
<h3>{employee.name}</h3>
<p>{employee.department}</p>
<p>{employee.salary}</p>
</div>
))}
</div>
);
}What is the problem?
- React creates elements for all 10,000 records.
- The browser must create and maintain a large DOM tree.
- Rendering and updating the list can become expensive.
- Scrolling may become slow, especially when each row contains multiple elements.
- Filtering and sorting large collections can also consume significant processing time.
The solution is not simply to use React.memo everywhere. We need to reduce the amount of work React and the browser perform.
2. Use List Virtualization (Windowing)
What is list virtualization?
List virtualization is a technique in which React renders only the records currently visible in the viewport, along with a small number of additional records.
Instead of rendering all 10,000 records, it might render only 20–40 rows at a time.
As the user scrolls, the visible records are replaced with the appropriate records.
Without virtualization:
Popular libraries:
- react-window: A lightweight library for rendering only visible list items. Check its current API and maintenance status before choosing it for a new project.
- @tanstack/react-virtual: A flexible headless virtualization library that supports lists, grids, and other virtualized layouts.
- react-virtuoso: A virtualization library with convenient support for variable-height items and more advanced list scenarios.
Example using @tanstack/react-virtual First, install the package:
npm install @tanstack/react-virtual
Implementation:
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
function EmployeeList({ employees }) {
const parentRef = useRef(null);
const rowVirtualizer = useVirtualizer({
count: employees.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 60,
overscan: 5
});
return (
<div
ref={parentRef}
style={{
height: "400px",
overflow: "auto"
}}
>
<div
style={{
height: rowVirtualizer.getTotalSize(),
width: "100%",
position: "relative"
}}
>
{rowVirtualizer.getVirtualItems().map(row => {
const employee = employees[row.index];
return (
<div
key={employee.id}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: row.size,
transform: `translateY(${row.start}px)`
}}
>
<strong>{employee.name}</strong>
<p>{employee.department}</p>
</div>
);
})}
</div>
</div>
);
}How does it work?
useRefstores the scrollable container reference.useVirtualizercalculates which rows should currently be visible.countspecifies the total number of records.estimateSizeprovides the estimated height of each row in pixels.overscanrenders a few additional rows outside the visible area to make scrolling smoother.getVirtualItems()returns the rows that need to be rendered.getTotalSize()calculates the total virtual height so the scrollbar represents the complete list.
When should you use virtualization? Use it when:
- You need to display thousands of records.
- Rendering all rows causes noticeable performance problems.
- Users need to scroll through a large dataset.
- Each row contains complex UI elements.
3. Use Pagination
What is pagination?
Pagination divides a large dataset into smaller pages and displays only one page at a time.
For example, instead of displaying 10,000 employees together, display 50 employees per page.
Example:
function EmployeeList({ employees }) {
const [currentPage, setCurrentPage] = useState(1);
const pageSize = 50;
const totalPages = Math.ceil(
employees.length / pageSize
);
const startIndex = (currentPage - 1) * pageSize;
const currentEmployees = employees.slice(
startIndex,
startIndex + pageSize
);
return (
<>
{currentEmployees.map(employee => (
<div key={employee.id}>
{employee.name}
</div>
))}
<button
disabled={currentPage === 1}
onClick={() => setCurrentPage(p => p - 1)}
>
Previous
</button>
<span>
Page {currentPage} of {totalPages}
</span>
<button
disabled={currentPage === totalPages}
onClick={() => setCurrentPage(p => p + 1)}
>
Next
</button>
</>
);
}Advantages:
- Reduces the number of rendered records.
- Easy to implement and understand.
- Works well with server-side data retrieval.
- Provides predictable navigation for users.
Important: Client-side pagination reduces the number of rendered rows, but the complete dataset is still downloaded and stored in the browser. For very large datasets, server-side pagination is generally preferable.
When should you use pagination?
Use it for employee directories, product catalogs, transaction histories, reports, and administrative tables where users need to navigate between pages.
4. Use Server-Side Pagination
For very large datasets, avoid downloading every record to the browser.
Instead, request only the required page from the backend.
Example API:
GET /api/employees?page=1&pageSize=50
Example response:
{
"items": [
{
"id": 1,
"name": "John",
"department": "IT"
},
{
"id": 2,
"name": "David",
"department": "HR"
}
],
"totalCount": 10000,
"page": 1,
"pageSize": 50
}React implementation:
function EmployeeList() {
const [employees, setEmployees] = useState([]);
const [page, setPage] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const pageSize = 50;
useEffect(() => {
const controller = new AbortController();
async function loadEmployees() {
try {
const response = await fetch(
`/api/employees?page=${page}&pageSize=${pageSize}`,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to load employees");
}
const data = await response.json();
setEmployees(data.items);
setTotalCount(data.totalCount);
} catch (error) {
if (error.name !== "AbortError") {
console.error(error);
}
}
}
loadEmployees();
return () => controller.abort();
}, [page]);
const totalPages = Math.ceil(totalCount / pageSize);
return (
<>
{employees.map(employee => (
<div key={employee.id}>
{employee.name} - {employee.department}
</div>
))}
<button
disabled={page === 1}
onClick={() => setPage(p => p - 1)}
>
Previous
</button>
<span>Page {page} of {totalPages}</span>
<button
disabled={page >= totalPages}
onClick={() => setPage(p => p + 1)}
>
Next
</button>
</>
);
}
Why use AbortController?
If the user quickly changes pages, an earlier API request may still be running. AbortController cancels the previous request when the effect cleans up, helping prevent outdated responses from replacing newer results.
Backend considerations:
- Apply pagination in the database query rather than loading all records into memory.
- Use appropriate database indexes for filtering and sorting.
- Return total count when the UI needs to display the total number of pages.
- For rapidly changing or extremely large datasets, consider cursor-based pagination instead of offset-based pagination.
5. Use React.memo for List Items
Even after reducing the number of records, individual rows may re-render unnecessarily.
React.memo can help when a row receives unchanged props.
Example:
const EmployeeRow = React.memo(function EmployeeRow({
employee
}) {
console.log("Rendered:", employee.name);
return (
<div>
<strong>{employee.name}</strong>
<p>{employee.department}</p>
</div>
);
});
function EmployeeList({ employees }) {
return (
<>
{employees.map(employee => (
<EmployeeRow
key={employee.id}
employee={employee}
/>
))}
</>
);
}What happens?
- React.memo compares the employee prop.
- If the same employee object is passed again, the row can skip rendering.
- If the employee object changes, the row renders again.
Important: If the parent recreates every employee object on every render, React.memo may not provide the expected benefit. Preserve object references where appropriate and update only the records that actually change.
6. Use Stable and Unique Keys
React uses keys to identify list items between renders.
Incorrect:
{employees.map((employee, index) => (
<EmployeeRow
key={index}
employee={employee}
/>
))}
Using array indexes as keys can cause problems when records are inserted, deleted, or reordered.
Correct:
{employees.map(employee => (
<EmployeeRow
key={employee.id}
employee={employee}
/>
))}
Benefits of stable keys:
- Helps React identify which items have changed.
- Prevents incorrect component state from being associated with another list item.
- Improves reconciliation when records are inserted, removed, or reordered.
Keys should be unique among siblings and stable across renders. Avoid generating random keys during rendering.
7. Optimize Filtering and Sorting
Filtering and sorting large datasets can be expensive.
Example without useMemo:
function EmployeeList({ employees }) {
const [search, setSearch] = useState("");
const filteredEmployees = employees.filter(employee =>
employee.name
.toLowerCase()
.includes(search.toLowerCase())
);
return (
<>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Search employees"
/>
{filteredEmployees.map(employee => (
<div key={employee.id}>
{employee.name}
</div>
))}
</>
);
}
The filtering operation runs whenever the component renders.
Optimized with useMemo:
const filteredEmployees = useMemo(() => {
return employees.filter(employee =>
employee.name
.toLowerCase()
.includes(search.toLowerCase())
);
}, [employees, search]);
Now React can reuse the filtered result when neither employees nor search has changed.
For very large datasets:
Consider performing filtering and sorting on the server. This avoids downloading and processing records that the user does not need.
8. Avoid Unnecessary Parent Re-renders
When a parent component re-renders, its child components are normally considered for rendering again.
A large list can become expensive if the parent frequently updates unrelated state.
Example:
function Dashboard({ employees }) {
const [clock, setClock] = useState(0);
const [selectedEmployee, setSelectedEmployee] = useState(null);
return (
<>
<p>Clock: {clock}</p>
<EmployeeList employees={employees} />
</>
);
}
If clock changes frequently, the employee list may also be rendered again.
Possible improvements:
- Move unrelated state into a smaller component.
- Use React.memo for expensive child components when appropriate.
- Keep object and function props stable when they are passed to memoized components.
- Avoid placing frequently changing state in a Context consumed by every list row.
9. Use useDeferredValue for Responsive Search
When filtering a large list, typing into a search box may become slow because filtering and rendering compete with user input updates.
React provides useDeferredValue to let less urgent UI updates lag behind more urgent updates.
Example:
function EmployeeSearch({ employees }) {
const [search, setSearch] = useState("");
const deferredSearch = useDeferredValue(search);
const filteredEmployees = useMemo(() => {
return employees.filter(employee =>
employee.name
.toLowerCase()
.includes(deferredSearch.toLowerCase())
);
}, [employees, deferredSearch]);
return (
<>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Search employees"
/>
{filteredEmployees.map(employee => (
<div key={employee.id}>
{employee.name}
</div>
))}
</>
);
}
How does it work?
- The search input updates immediately.
- React can defer updating the filtered list when more urgent work needs attention.
- The list eventually catches up with the latest search value.
10. Use useTransition for Non-Urgent Updates
useTransition allows React to mark certain state updates as non-urgent transitions.
This is useful when an expensive UI update should not block important user interactions, such as typing into a search box.
Example:
function EmployeeSearch({ employees }) {
const [search, setSearch] = useState("");
const [filter, setFilter] = useState("");
const [isPending, startTransition] = useTransition();
function handleSearch(value) {
setSearch(value);
startTransition(() => {
setFilter(value);
});
}
const filteredEmployees = employees.filter(employee =>
employee.name
.toLowerCase()
.includes(filter.toLowerCase())
);
return (
<>
<input
value={search}
onChange={e => handleSearch(e.target.value)}
placeholder="Search employees"
/>
{isPending && <p>Updating results...</p>}
{filteredEmployees.map(employee => (
<div key={employee.id}>
{employee.name}
</div>
))}
</>
);
}
How does it work?
- The search input state updates urgently.
- The filter state update is marked as a transition.
- React can prioritize the input interaction over the list update.
isPendingindicates whether the transition is pending.
11. Choose the Right Optimization Technique
| Technique | Purpose | Best suited for |
|---|---|---|
| Virtualization | Render only visible rows | Thousands of records |
| Client-side pagination | Display a limited number of loaded records | Small or medium datasets |
| Server-side pagination | Retrieve only the required records | Large database tables |
| React.memo | Skip unnecessary component rendering | Expensive list rows |
| useMemo | Reuse calculated values | Expensive filtering and sorting |
| useCallback | Reuse function references | Callbacks passed to memoized children |
| useDeferredValue | Defer less urgent UI updates | Search and filtering interfaces |
| useTransition | Mark updates as non-urgent | Expensive state-driven UI updates |
12. Recommended Approach for a Real-World Application
Consider an enterprise application displaying 100,000 employee records. A good architecture would be:
Recommended implementation strategy:
- Backend: Implement server-side filtering, sorting, and pagination.
- API: Return only the records required for the current page.
- React: Store only the necessary records in component state.
- Virtualization: Use it when a page itself contains many rows or when implementing continuous scrolling.
- Memoization: Use React.memo, useMemo, and useCallback only where profiling identifies unnecessary work.
- Search: Debounce server requests when appropriate to avoid sending an API request for every keystroke.
- Monitoring: Use React DevTools Profiler and browser performance tools to identify bottlenecks.
13. Common Mistakes to Avoid
- Rendering thousands of records unnecessarily: Use pagination or virtualization.
- Using array indexes as keys: Prefer stable record identifiers.
- Memoizing every component: Memoization has overhead; optimize based on profiling.
- Downloading the complete database result: Prefer server-side pagination for large datasets.
- Filtering repeatedly: Use useMemo when the calculation is expensive and dependencies are stable.
- Making API requests on every keystroke: Consider debouncing or a suitable data-fetching strategy.
- Ignoring variable row heights: Configure the virtualization library to measure or correctly estimate dynamic row sizes.
- Using virtualization without considering accessibility: Ensure keyboard navigation, focus management, and screen-reader behavior remain usable.
14. Interview Questions and Answers
Q1. What is list virtualization in React? List virtualization is a technique that renders only the visible portion of a large list instead of rendering all records at once. It reduces DOM elements and improves scrolling performance.
Q2. What is the difference between pagination and virtualization? Pagination divides records into separate pages and displays one page at a time. Virtualization renders only the visible rows within a scrolling area. They can also be used together.
Q3. Which React libraries are commonly used for virtualization? Common options include @tanstack/react-virtual, react-window, and react-virtuoso.
Q4. Why should we use React.memo for list items? React.memo can prevent a list item from re-rendering when its props have not changed. It is useful when list rows are expensive to render.
Q5. Why are stable keys important in React lists? Stable keys help React identify individual list items during reconciliation, especially when items are inserted, deleted, or reordered.
Q6. What is server-side pagination? Server-side pagination retrieves only a specific portion of records from the backend instead of downloading the complete dataset.
Q7. What is the difference between useDeferredValue and useTransition? useDeferredValue lets a value used by less urgent UI work lag behind its latest value. useTransition lets developers explicitly mark state updates as non-urgent.
Q8. Does useMemo improve list rendering automatically? No. useMemo can avoid repeating expensive calculations, such as filtering and sorting. It does not reduce the number of DOM elements rendered. Virtualization addresses that problem.
Q9. How would you optimize a React page containing 100,000 records? I would implement server-side filtering, sorting, and pagination to reduce the amount of data transferred. For large visible result sets, I would use virtualization. I would also profile rendering, use stable keys, and apply memoization selectively.
Q10. How do you identify performance issues in a large React list? Use React DevTools Profiler to identify unnecessary component renders and browser performance tools to inspect scripting, layout, painting, and scrolling performance.
15. Quick Summary
- Virtualization: Render only visible list items.
- Pagination: Divide records into smaller pages.
- Server-side pagination: Fetch only the required records from the backend.
- React.memo: Avoid unnecessary list-item re-renders.
- useMemo: Avoid repeating expensive filtering and sorting calculations.
- useCallback: Maintain stable callback references where needed.
- useDeferredValue: Keep user interactions responsive during expensive UI updates.
- useTransition: Mark less urgent state updates as transitions.
- Stable keys: Help React correctly identify list items.
Most important takeaway: For very large datasets, start by reducing the amount of data retrieved and rendered. Use server-side pagination and virtualization where appropriate, then optimize individual components based on actual performance measurements.
| React-memo-vs-useMemo-vs-useCallback :👈 | 👉:Implement Virtualization for Long Lists |
Comments and Discussion