5

I've just started writing some custom hooks and the question popped up, should I return a set of values as an array or as an object?
Is there a specific reason that useState returns an array of a pair values and not an object with two properties?
I feel like I've read something about this but can't recollect where. Thanks

Vishwas
  • 1,398
  • 8
  • 20
  • 33

1 Answers1

3

To expand on @Vishwas comment, it has to do with naming.

This is briefly mentioned in the fine print of the useState docs.

When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.

const [someValue, someUpdateFunction] = useState(0);

Under the hood React process the data at array[0] as the current value, and the data at array[1] as an update function. Only the position matters, not the naming. When devs implement useState, they can provide meaningful names to the values at those positions.

lusc
  • 1,206
  • 1
  • 10
  • 19
It'sNotMe
  • 1,184
  • 1
  • 9
  • 29