Build a virtual list using hook from scratch to deal with large dataset

Indie Dev
2 min readNov 25, 2021

--

Photo by Glenn Carstens-Peters on Unsplash

In recent projects, I had to deal with a large dataset in frontend side. First, I tried to use react-virtualized which is a great library to deal with my problems. But after that, I decided to reinvent the wheel to get some fun.

The concept behind the virtual list

  • Render only necessary items that fit into the container which contains the item. Unmount the items outside the viewport.
  • Render some buffered items to make the scrolling smoothly.
  • Whenever scrolling, we will do above 2 stuff again and again.
Our code will try to re-calculate the visible range and re-render

The interface of component

First, I tried to combine all stuff inside the component. The code became messy. So I separated them into 2 parts: useVirtualList and VirtualList.

With this approach, we can separate the concern UI Logic Handler and UI Presenter. Then we can test it easier.

The VirtualList wrapper
The scaffold of useVirtualHook

The testing of useVirtualList

  • I used the testing-library to test this hook. (renderHook)
  • Use jest to mock the property of containerEl/listEl (jest.spyOn)

For the full repository, you can take a look at https://github.com/namKolo/hookdafish

I am very appreciated if you have any feedbacks. Please open the issues if you found any problems. Thanks.

--

--

Indie Dev
Indie Dev

No responses yet