Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Basic] Custom hooks recommendation idea #100

Closed
ravihugo opened this issue Mar 26, 2019 · 3 comments
Closed

[Basic] Custom hooks recommendation idea #100

ravihugo opened this issue Mar 26, 2019 · 3 comments
Assignees
Labels
BASIC Basic Cheatsheet

Comments

@ravihugo
Copy link

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 ravihugo added the BASIC Basic Cheatsheet label Mar 26, 2019
@ferdaber
Copy link
Collaborator

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()
}

@swyxio
Copy link
Collaborator

swyxio commented Mar 27, 2019

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
Copy link
Collaborator

swyxio commented Apr 17, 2019

closing as not actionable

@swyxio swyxio closed this as completed Apr 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BASIC Basic Cheatsheet
Projects
None yet
Development

No branches or pull requests

3 participants