Build a virtual list using hook from scratch to deal with large dataset
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.
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 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.