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
Asked
Active
Viewed 1,265 times
5

Vishwas
- 1,398
- 8
- 20
- 33
-
4Because it's easier for the user to name the array values. – JJJ Jul 14 '19 at 08:58
-
Makes sense, thanks – Vishwas Jul 14 '19 at 09:12
1 Answers
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.