7 ms·
> Flaw 2: One common suggestion is to let useState() accept a key argument (e.g. a string) that uniquely identifies a particular state variable within a compone
by maaaats 8y ago
> Flaw 2: One common suggestion is to let useState() accept a key argument (e.g. a string) that uniquely identifies a particular state variable within a component.
I tried asking about that earlier here on HN[0], nice to finally at least get an explanation. The tldr is name clashes when reusing hooks. A valid concern, I think they should be more upfront about the reasoning instead of "hooks are magic, don't use them in these ways". That would make it easier to accept.
[0]: https://news.ycombinator.com/item?id=18640612 https://news.ycombinator.com/item?id=18640612 (and the blogpost in the answer didn't really answer it)
- k__ 8y agoWouldn't symbols solve this issue?
- genezeta 8y agoYes, and to some extent it is addressed in the link too (though not really well explained). Symbols do not clash, but they need to be managed/stored by client code. i.e. you need to keep the original Symbol to use it in different calls, while you can use "different equal strings". This is the argument in the article. Whether this is indeed more or less desirable than having order restrictions on calls, that's a different thing. I personally think it is indeed a better solution, but the React team seems to think it's not.
- k__ 8y agoI guess changing call orders is an edge-case, so why optimize for it.
- danabramov 8y agoSymbols don't solve this without extra closure wrapper and Hook "instantiation" (described in flaw #5). Passing a Symbol to custom Hook from outside also doesn't work because a custom Hook may have more than one state. Try to convert the `useSubscription` example to your proposed API (and don't forget effects would also need "IDs") and you'll see what I mean.
- k__ 8y agoCouldn't a custom hook have a map of maps that keep track of this? The first map gets the symbol that was passed to the custom hook as keys and the maps inside that map would use symbols only the custom hook knows about. I think your solution is superior in that is more concise and I at least think I understand why you went that way. I'm just trying to understand why the symbol approach wouldn't work.
- danabramov 8y agoYeah you could do this but this “breaks copy paste” (one of the flaws). We want creating a custom Hook to feel exactly like extracting a function. It should feel easy and you shouldn’t need to mess with maps and symbols.
- k__ 8y agoOkay, DX is an important selling factor, so your approach seems reasonable to me.
- danabramov 8y agoRuntime performance is another one. Map lookups aren’t free, especially if there’s a whole bunch of them happening in every component on every render.
- k__ 8y agoYes, the order restriction buys a lot of things rather cheaply. And while I trust the React teams judgement, I teach people React and they often question the "why".