streamich/react-use

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

Open

#1,188 建立於 2020年5月4日

在 GitHub 查看
 (8 留言) (4 反應) (0 負責人)TypeScript (43,979 star) (3,273 fork)batch import
enhancementgood first issuehelp wanted

描述

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.

貢獻者指南