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.
Share Improve this question asked Mar 18, 2019 at 5:20 bunnybunny 2,0378 gold badges37 silver badges66 bronze badges 3 |1 Answer
Reset to default 23The 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.
setCount()
to update the value ofcount
. I believe you may destructure it usinglet
orvar
but usingconst
helps prevent mutation. – Miroslav Glamuzina Commented Mar 18, 2019 at 5:24