Today I encountered a long list of optimization problems during the whole project. I wanted to do data paging, but I needed to talk to the background. My rule is to try not to bother people, so I searched for some solutions and finally found a solution on the React official – virtual list.

Virtual list

Let’s take a look at the official introduction.

“Virtual lists are a” virtual scroll “technology. This technique renders only a limited amount of content in a limited amount of time and miraculously reduces the amount of time it takes to re-render components and the number of DOM nodes created.”

It really looks like we can optimize the long list, so let’s give it a try.

Using virtualized tables on react requires a mode called Act-Virtualized.

You can go to the home page for details.

Virtual list implementation process

In order to quickly implement the virtualization list, I will skip the basic configuration and start directly with the virtualization package.

First, let’s install the virtualization package.

npm i react-virtualized
Copy the code

This package exposes some component apis. Here we use the List component.

For an introduction to the properties of this component, we can look at github addresses.

Let’s look at a few of them

  • Width Specifies the width of the List component

  • Height Height of the List component

  • RowHeight The height of each row

  • RowRenderer A function to be executed for each row rendered

The code is as follows:

import React,{ Component,useState,useEffect,Fragment,Suspense} from "react" import {List} from 'react-virtualized'; Function getArr() {let arr = [] for(var I =0; i<1000; i++){ arr.push({name:"zhangsan"+i}) } return arr } let arr = getArr() console.log(arr) function App() { return( <> <List  width={400} height={200} rowCount={arr.length} rowHeight={40} rowRenderer={rowRenderer}/> </> ) } function rowRenderer({key,index,style}) { return ( <div key={key} style={style}>{arr[index].name}</div> ) } export default AppCopy the code

In the page, we can see the following form.

In the review element, we’ll always have these five divs in our code, and there won’t be many, depending on what the view shows.