Should React Hooks return Array or Object?

David
3 min readOct 11, 2021

Have you ever been confused about the return of a React Hook before? Most of the time, you will see the hooks returning an array, don’t you? Can we return an object in React Hook? And which cases do we use it?

Which one should we choose? Return an Array or an Object?

Array vs Object

An array is also the object type

When we use the typeof to check an array, we receive the object output. Arrays are objects in JavaScript.

Two Array and Object are the references to the memory they keep their value.

So two ways of writing the React Hooks are valid, it just returns the reference. The difference is how we can get the value of the array or the object returned

Get values from an array

  • Must get the values in the order
  • Naming variables easily by any name you want
the example of getting values from an array

Get values from an object

  • Must get values with the proper fields of the object
  • Harder to name the other variables
the example of getting values from an object

Usage

Using array return in case:

  • Using multiple instances of a hook in a component. So we can be flexible to use any variable names.
using multiple instances of useState Hook
  • You know the proper order of the return value, like: [value, setValue]

Using object return in case:

  • Using one or two instances of a hook in a component. So we don’t need to rename the variables because of the name conflict.
using one instance of a useLoading Hook
  • You don't know the proper order of the return value, like [isLoading, hideLoading, showLoading] or [isLoading, showLoading, hideLoading].

I recommend you use the hook to return an array. If you see it’s not good, then write it in object return.

Thanks for reading. I hope this article is useful for you. If you see some mistakes in the post, don't hesitate to let me know, I will check and fix it later.

My name is David, I am a web developer. I love technology, and I will share more articles about Web Development, ReactJS, and JavaScript. You can read more here. Thank you!

--

--

David

I love technology, and I wanna build good products to make life better. I will share my knowledge about Web Development, ReactJS, and JavaScript.