Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why useState returns array in React

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading