DEV Community

Cover image for πŸͺ Why useState returns an array in React?
Anthony
Anthony

Posted on • Updated on

πŸͺ Why useState returns an array in React?

I have always wondered why does React useState returns an array instead of an object.

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

This assigns the current state value to the count variable, and the update function to the setCount variable. This syntax is concise and easy to read, making it a popular choice for managing state in React.

If useState were to return an object instead of an array, you would need to use property destructuring to access the state value and update function. This can be more verbose, as you would need to provide an explicit property name for each value:

const {state: count, setState: setCount} = useState(0);
Enter fullscreen mode Exit fullscreen mode

If useState returns an Object the destructring assignment wouldn't be that convenient, because you'd have to implicitly rename the object fields. And if don't rename the object fields, then we would only be able to use only one useState in a component.

This syntax is less convenient than array destructuring, as you need to rename the properties of the returned object to avoid naming conflicts. If you don't rename the properties, you would only be able to use one useState call in a component.

Overall, using an array to return the state value and update function is a simple and effective way to manage state in React. While returning an object would be possible, it would require more verbose syntax and would be less convenient for most use cases. By returning an array, React makes it easy to use useState to manage state in your functional components.

Top comments (0)