10

I am currently learning React and React hook. A classic example of using useState is as below:

const [count, setCount] = useState(0);

My question is why the returned array is const? I think at least the value of count is changed over time.

bunny
  • 1,797
  • 8
  • 29
  • 58
  • Possible duplicate of [Javascript object bracket notation ({ Navigation } =) on left side of assign](https://stackoverflow.com/questions/26999820/javascript-object-bracket-notation-navigation-on-left-side-of-assign) and [What is destructuring assignment and its uses?](https://stackoverflow.com/questions/54605286) – adiga Mar 18 '19 at 05:21
  • Possible duplicate of [What is destructuring assignment and its uses?](https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses) – Code Maniac Mar 18 '19 at 05:23
  • 2
    You're not supposed to mutate state. In order to correctly update your values, you should use `setCount()` to update the value of `count`. I believe you may destructure it using `let` or `var` but using `const` helps prevent mutation. – Miroslav Glamuzina Mar 18 '19 at 05:24

1 Answers1

22

The value returned by useState is not a const array, rather its just an array which the user has decided to declare as const. Think of the above as

const stateValue = useState(0);
const count = stateValue[0];
const setCount = stateValue[1];

So in short, the syntax const [count, setCount] = useState(0); is an Array destructuring syntax.

Not its is declared as const because you are not reassigning count or setCount to something else in your code, instead just using setCount method to update the state count.


React authors decided to return an array with state value and state setter so that you can name it anything you want instead of using a pre-decided name while destructuring.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 8
    "so that you can name it anything you want instead of using a pre-decided name while destructuring" that is answer I was looking for! – Rodrigo Saling Apr 08 '20 at 20:29
  • If useState would return an object then the names would be fixed, which means you cannot have multiple occurrences of useState in the same component. – MarcFasel Aug 03 '21 at 03:50
  • Aah, the naming makes sense, so even though you could have used an alias like const { value: myValue, setter: setMyValue} = useState, that would have been annoying for all the useStates you are likely to use in a component – Jarrod McGuire Mar 23 '22 at 13:34