streamich/react-use

Idea: rewrite `useSet` and `useMap` to avoid building a new instance on each update

开放

#1,188 创建于 2020年5月4日

 (8 条评论) (4 个反应) (0 位负责人)TypeScript (3,273 个派生)batch import
enhancementgood first issuehelp wanted

仓库指标

星标
 (43,979 个星标)
PR 合并指标
 (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

https://github.com/streamich/react-use/blob/0572ced9f861a21bcab5402eb2b4413697c462c3/src/useSet.ts#L19-L20

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.

贡献者指南