How to optimize large lists in React?
Large lists can slow down React apps because rendering thousands of DOM nodes at once is expensive.
To optimize large lists:
-
Use windowing or virtualization
Render only visible items instead of the whole list. -
Use
React.memo
for list items
Prevent re-rendering of list items that haven't changed. -
Use pagination or lazy loading
Fetch and render a limited number of items at a time. -
Use keys efficiently
Provide a stable, uniquekey
prop to each item. -
Debounce scroll handlers
If list interactions involve scrolling, debounce heavy computations like fetching or UI updates.
Example with virtualization:
Using react-window
:
import { FixedSizeList as List } from 'react-window'; const MyList = ({ items }) => ( <List height={500} itemCount={items.length} itemSize={35} width={300} > {({ index, style }) => <div style={style}>{items[index]}</div>} </List> );
This drastically reduces the number of rendered DOM nodes!