Idea: rewrite `useSet` and `useMap` to avoid building a new instance on each update
#1,188 创建于 2020年5月4日
仓库指标
- Star
- (43,979 star)
- PR 合并指标
- (平均合并 1743天 9小时) (30 天内合并 1 个 PR)
描述
The problem
I noticed these two hooks are effectively re-implementing the native Set and Map classes, and performing some potentially expensive operations on them. Ex:
https://github.com/streamich/react-use/blob/master/src/useSet.ts https://github.com/streamich/react-use/blob/master/src/useMap.ts
Here we're creating a copy of the set by transforming it into an array via Array.from. Then, we're performing a filter or a spread operator on them to emulate what Set#add and Set#delete would be doing.
Solution
Inspired by mobx-react-lite and how they handle Set and Map, followed by forcing a re-render, I decided to try to build a custom hook for vanilla React.
Here's a proof of concept: https://codesandbox.io/s/react-set-map-hooks-proxy-v9wzw?file=/src/App.js
Essentially, instead of relying on useState to trigger updates, requiring us to copy and re-instantiate our Set, I'm using useRef to store the Set object. I also implemented Proxy to help keep the API the exact same so no custom functions are required.
I've yet to do performance tests, but plan to soon. I'd love to see this in use on large data sets so it can take advantage of Set's built-in optimizations.