As from the documentation from Hooks in Reactjs,
const [count, setCount] = useState(0);
they use array destructuring. Can we use object destructuring in place of array destructuring?
I totally agree with answer given by @Patrick. Since react team implemented it adhere to all use cases. There's no need actually to put return values in object since it doesn't need to access it via keys or later need to update. One edge here is Destructuring part is way more easy for arrays than objects.
As we have seen const [count, setCount] = useState(0);
we can use any name for count and setCount. In Objects we need to do it like this:
// grab the state value and setState func but rename them to count and setCount
const { stateValue: count, setState: setCount } = useState(0);
in arrays:
// grab in order and rename at the same time
const [count, setCount] = useState(0);
useState returns an array, so no, in this case, you have to use array destructuring.
To clarify, this doesn't mean that all React hook functions need to return an array.
If you create your own hook, you can have it return whatever you like, including an object, which you can destructure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With