ama
ama copied to clipboard
Deconstructing from a custom hook
Not really a code help, but more of a suggestion for a next article!
const [a,b,c] = useMyHook()
vs
const {a,b,c} = useMyHook()
When to use one over the other? I really like the first approach, but a bit annoying when you need the first and fifth ones only. const [a,,,,e] = useMySecondHook()
might reflect an non-optimal API.
There are few solutions but it would be great to have your thoughts on that in an article, because I am not sure I am the only one.
Thanks! Karl
The array destructuring pattern came about so people could name what's returned from hooks whatever they want.
Consider the useState
hook. Imagine if it returned { state, setState }
. There'd be two issues: 1. you couldn't easily give them descriptive names. 2. If you use two useState
hooks in a component, you couldn't destructure them both because they have the same keys.
Thanks for your comment @hedgerh! I totally get your point and like I said the array destructuring is the approach I like (I should have said prefer). Your comment adds more details to my thoughts. However, my suggestion was more about the best practices when we design custom hook APIs.
Also, worth mentionning, you can easily rename the destructured variable name.