streamich/react-use

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

オープン

#1,188 opened on 2020/05/04

 (8 件のコメント) (4 件のリアクション) (0 人の担当者)TypeScript (3,273 件のフォーク)batch import
enhancementgood first issuehelp wanted

Repository metrics

Stars
 (43,979 個のスター)
PR merge metrics
 (PR metrics pending)

説明

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.

コントリビューターガイド