React·100 questions

How to avoid re-renders of a large list (1000+ items)?

Answer

Optimizing the rendering of large lists containing a thousand or more items is one of the classic tasks of frontend development in React. The browser spends a colossal amount of resources on creating, updating, and deleting hundreds of elements in the DOM tree if you try to render them all simultaneously. To prevent the interface from freezing during scrolling, developers have to apply a comprehensive approach to managing list performance.

The most effective solution for large-volume lists is virtualization, which will be discussed in more detail later. However, apart from that, there are several important rules. Each list item should be as simple and lightweight a component as possible, not overloaded with extra markup. It is extremely crucial to use stable and unique keys in the key property, such as database IDs, while avoiding the use of array indices if the order of elements can change. Heavy mathematical calculations or data formatting should never be performed right during the rendering process—they must be extracted beforehand.

To implement optimizations in a project with a list, it is recommended to follow a specific sequence of actions.

Analyze the list using the React DevTools Profiler to find bottlenecks and redundant re-renders.
Connect a virtualization library, such as react-window or react-virtualized, to render only the visible area.
Wrap list item components in React.memo so they do not re-render if their props haven't changed.
Extract event handlers and data mapping functions outside the body of the main component or memoize them using useCallback.

Adhering to these rules allows keeping the interface frame rate at 60 frames per second even on weak mobile devices. The user will be able to quickly scroll through long feeds of data or tables without annoying delays and interface stuttering.

Was this answer helpful?

More questions in this topic

Related questions from other topics