Idea: rewrite useSet and useMap to avoid building a new instance on each update
#1188
Comments
|
I would like to add that Proxy is not supported in older browsers like IE11. Also, why do we need to use Proxies here when we are already 'proxying' the backing set while returning add, remove, and other modifiers from the hook? We may add logic to these functions to force rerender when called. An ideal implementation would be to check if the set actually changed and needs rerender (yet this functionality should be configurable using a boolean flag like 'pure' to prevent adding a runtime penalty when it is not needed) |
|
I like the idea of providing the exact same APIs as But I'm skeptical about introducing |
|
Great points @laleksiunas @streamich! You could definitely have a pseudo "proxy" instead of |
|
@mattboldt I was thinking about a builder function that can create this kind of hooks, like the one below (just straight out of my mind, not tested):
And to use it:
What do you think? |
The problem
I noticed these two hooks are effectively re-implementing the native
SetandMapclasses, 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
react-use/src/useSet.ts
Lines 19 to 20 in 0572ced
Here we're creating a copy of the set by transforming it into an array via
Array.from. Then, we're performing afilteror a spread operator on them to emulate whatSet#addandSet#deletewould be doing.Solution
Inspired by
mobx-react-liteand 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
useStateto trigger updates, requiring us to copy and re-instantiate our Set, I'm usinguseRefto store the Set object. I also implementedProxyto 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.The text was updated successfully, but these errors were encountered: