React state, setState with const

Viewed 1442

Mostly I have seen in documentation and others code they wrote set hook like this picture in documentation:

enter image description here

in it they are changing count value by calling setCount. My question is that since count is declared with const keyword how is it changing on every setCount?

1 Answers

On re-renders, you are getting a new variable. setCount changes the value internally and ties the change into the life-cycle of the component. When a render occurs, you get a new count variable entirely, which is different than doing count = 9. Remember, components are just functions that are being called. Like any other function, each time you call it, you get a whole new set of variables scoped to it.

useState is returning an array with a value and a function, [9, () => {}]. All const [count, setCount] is doing is destructuring that array.

Related