I was trying to learn React hooks nowadays and useState API doesn't make any sense for me.
Why are we using array at all for one value and setter of that value? Is there any logical explanation for this particular design choice.
CodePudding user response:
The useState
hook needs to return two values: the current state and a function to change it. However, Javascript doesn't have any native way for functions to return several values, it can return only one value. But we can still fake multiple return values by returning a single value containing all the values we want to return. In the case of useState
, returning an array of length 2 is essentially the same as returning two values.
Another way to return several values would be to return an object with named fields {state, setState}
, but the problem is that it would be more clunky to use as you would need to explicitly rename the two fields:
const {state: value, setState: setValue} = useState();
// vs
const [value, setValue] = useState()
So basically it is just a nice way to return multiple values from a single function call.