ama icon indicating copy to clipboard operation
ama copied to clipboard

Deconstructing from a custom hook

Open karlguillotte opened this issue 5 years ago • 2 comments

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

karlguillotte avatar Apr 30 '19 23:04 karlguillotte

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.

hedgerh avatar May 01 '19 04:05 hedgerh

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.

karlguillotte avatar May 01 '19 04:05 karlguillotte