To understand this, let's dive into how arrays and objects destructing work.
Assume we have two functions returnsArray() and returnsObject() which returns ['item 1', 'item 2', 'item 3'] and { a: 'Item 1', b: 'Item 2', c: 'Item 3' } resp.
How can we extract values from the returnsArray() which returns ['item 1', 'item 2', 'item 3']?
- Without destructing:
const tempArray = returnsArray();
const variable1 = tempArray[0]; // Will be 'item 1'
const variable2 = tempArray[1]; // Will be 'item 2'
...
- With destructing:
const [variable1, variable2] = returnsArray();
You can clearly observe that destructing reduces the number of lines and makes the code more legible.
Note that the variable1 and variable2 are the custom variable names.
How can we extract values from the returnsObject() which returns { a: 'Item 1', b: 'Item 2', c: 'Item 3' }?
- Without destructing:
const tempObject = returnsObject();
const attribute1 = tempObject.a; // which is equal to 'Item 1'
const attribute2 = tempObject.b; // which is equal to 'Item 2'
...
- With destructing:
const { a, b } = returnsObject(); // if you want to the variable names as 'a' and 'b' or
const { a: attribute1 , b: attribute2 } = returnsObject(); // if you want to give custom
// variable names for the attributes 'a' and 'b'
You can clearly see that destructing reduces a lot of unwanted code and makes it more legible.
Now let's look at what will happen when we interchange both?
const [variable1, variable2] = returnsObject();
// above line literally translates to:
const tempObject = returnsObject();
const variable1 = tempObject[0]; // will be undefined
const variable2 = tempObject[1]; // will be undefined
Since we can not access the object's attributes by tempObject[0] & tempObject[1], both the variable values will be undefined.
Similarly,
const { variable1 , variable2 } = returnsArray();
// above line literally translates to:
const tempArray = returnsArray();
const variable1 = tempArray.variable1; // will be undefined
const variable2 = tempArray.variable2; // will be undefined
since tempArray doesn't have any attributes named variable1 & variable2. Both of those values will be undefined.
In your case, returnsArray() is useState() and returnsObject() is useContext().