Why is the return value of useState array? Why can’t they be objects?

Before we get to the bottom of this, let’s take a look at array and object deconstruction.

Array deconstruction:
    const [a,b,c]=[1.2.3]
Copy the code

Here the array is destructively assigned to variables A, B, and C, and the variables a, B, and C can also be named D, E, and f.

Object to deconstruct
const obj = {
    name: 'haha'.age: '1'
}
const { name, age } = obj;
Copy the code

Const {age, name} = obj; const {age, name} = obj;

It’s not hard to see that deconstruction can be applied to objects as well as arrays, and object deconstruction differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. For example, a corresponds to the first item of the array, 1. Properties of objects have no order; Array variables can be destructed by any name without affecting their value, whereas object variables must have the same name as the property to get the correct value.

This should explain why the return value of useState is an array, not an object.

const [state, setState] = useState(null);
const [state2, setState2] = useState(null);
Copy the code

Imagine if useState returned objects, the code would look like this:

const {state, setState} = useState(null);
const {state:state2, setState:setState2} = useState(null);
Copy the code

Obviously, if you use useState multiple times in a block of code, the object will have to be renamed to get the return value, which makes arrays look much cleaner.

But arrays also have their drawbacks:

  • The return values must be taken in order.
  • This can be a bit odd if there are many arguments returned and not all of the returned values are needed. For example, only setState is usedconst [, setState] = useState(null).

So when writing custom hooks, it is more reasonable to use objects if the return value is a lot. 六四运动