DEV Community

Discussion on: Write Custom Hooks in React

Collapse
 
pritampatil profile image
Pritam Patil

Wouldn't it be better to return an object from a custom hook rather than an array?

So instead of returning like this -

return [todos, addTodo, toggleTodo]
Enter fullscreen mode Exit fullscreen mode

We could choose to return -

return  { todos, addTodo, toggleTodo }
Enter fullscreen mode Exit fullscreen mode

This way I don't have to worry about the position at which my todos or method addToDo is accessible?

Collapse
 
mwoodson profile image
marques woodson

I don't know if I'd say one way is better than the other. I return arrays sometimes if there aren't a lot of objects being returned, but once I get more than 3 I would probably switch to returning an object. I also use a lot of Typescript, so defining the return type helps with not mixing up variables.