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.
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.
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.