Have you asked yourself how you can change the state you defined in spite of using const declarations like const [count,setCount] = useState(0)
? let's dive a little bit ...
The first question we need to ask is that does the const declarations make variables immutable.
actually, const creates something called constant reference to the value
which states that you can't change the reference of the variable but if you have an object or array you can easily edit it. so the real answer to the previous question is No
. Now let's back to our main topic:
we have received two variables from useState hook (by Destructuring)
so according to the above content we can't edit on count
variable, can we?
the answer is that we can't edit on count
variable directly without using setCount
and if you try to do that, you'll receive a Type Error indicating that count is a constant variable as shown in the main image.
so, what is the magic that setCount
is making ?
well, setCount
is a function provided by reacting and using its mechanisms like (virtual DOM..etc) to change the value of count
variable.
Top comments (0)