Array vs Object
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
Get values from an object
- Must get values with the proper fields of the object
- Harder to name the other variables
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.
- 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.
- 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!