When I console.log the value of count, it increases by 1 even though I
have declared it using const.
When you are console logging the count state you are actually logging the unupdated current state value. In other words, nothing has changed yet. It's only at the end of the render cycle when enqueued state updates are processed that the component rerenders (i.e. calls the function body) with the updated state value.
How is it still being updated? I have a feeling it's related to the
useState function, but I'm not sure.
Yes, the useState hook returns the current state value and a function to call to enqueue an update to state.
const [count, setCount] = useState(0);
In the increase callback handler the setCount function is called with the next value you are requesting React to update the state to.
function increase() {
setCount(count + 1);
}
As described above, the update is enqueued and at then end of the render cycle is processed by React and triggers the component to rerender.
Another thing is, if we can update using count + 1, why can't we do so
using count++?
In React we absolutely DO NOT mutate state. The count++, if it could work and not throw an error, would still be a state mutation. Trying to use count++ is the same as trying to do count = count + 1 which we just simply don't do in React.
In more general Javascript terms, trying to post-increment with count++ while count is declared const would throw an error. When a variable is declared const this only means it can't have a value reassigned to it after initialization. This doesn't mean that the value currently assigned is static/constant. If we had declared let [count, setCount] = useState(0) then by Javascript standards doing count++ is perfectly legal.
We use the React state updater functions to enqueue state updates and generally return new object/value references.