react icon indicating copy to clipboard operation
react copied to clipboard

[Basic] Custom hooks recommendation idea

Open ravihugo opened this issue 7 years ago • 3 comments

What cheatsheet is this about? (if applicable)

Basic cheatsheet

What's your issue or idea?

Our team uses custom hooks a lot. We are testing out the idea to return objects rather than arrays. You see, it makes sense for the generic hook functions to return arrays because it's almost always useful to grab both the state and the setState function. Also the react provided hooks don't really know what you're going to "call" or "name" the hook variables. However when you write a custom hook it's very useless to return an array because you're now requiring the caller to grab and name every variable that is returned (up until the last variable they plan on using). With an object return, you provide a bag of named variables (which makes much more sense for a custom hook). That way the caller of the hook can decide to grab JUST the variables they might be interested in, and are not forced to make unused variables if they just want the setter, for example.

ravihugo avatar Mar 26 '19 16:03 ravihugo

Did you know that you can just grab whatever you want out of an array?

function useCustomHook() {
  return [42, true, () => null, 'abc', { foo: 'bar' }] as const
}

function MyComponent() {
  // only grabs indices 0, 2, and 3 out of the array
  const [myNum,,myFunc,myString] = useCustomHook()
}

ferdaber avatar Mar 26 '19 17:03 ferdaber

to be fair though, for returning more than 2 values i'd recommend returning an object. unfair to expect people to remember return order beyond that. (subjective opinion)

returning an object is easy tho? esp with inferred return values. could you clarify what you think we could add or change on the cheatsheet @ravihugo ?

swyxio avatar Mar 27 '19 20:03 swyxio

closing as not actionable

swyxio avatar Apr 17 '19 23:04 swyxio