function App() {
const [count, setCount] = useState(0);
function increase() {
setCount(count + 1);
console.log(count);
}
return (
<div>
<h1>{count}</h1>
<button onClick={increase}>+</button>
</div>
);
}

When I console.log the value of count, it increases by 1 even though I have declared it using const. How is it still being updated? I have a feeling it's related to the useState function, but I'm not sure.
Another thing is, if we can update using count + 1, why can't we do so using count++?
Thanks a lot for the guidance!
Code is here: https://codesandbox.io/s/g8dgv0?file=/src/components/App.jsx
React is fundamentally a rendering library, and the paradigm it uses is that the info that's rendered on the screen should flow directly from the current state stored in React. So, calling a state setter does two things:
Whenever a functional component re-renders, the function runs again - and useState can return different values depending on what the current value of the internal state is.
For a similar example in vanilla JS:
let internalValue = false;
const getValue = () => internalValue;
const setValue = (newValue) => {
internalValue = newValue;
setTimeout(App);
};
const App = () => {
const stateValue = getValue();
if (!stateValue) {
setValue(true);
}
console.log('app rendered with stateValue of', stateValue);
};
App();
Above, you can do const stateValue = getValue(); and get different values for stateValue depending on other factors - because the App function ran again.
Another thing is, if we can update using count + 1, why can't we do so using count++?
Because, as explained in the beginning of the answer, the view should flow from the state in React, and when updating the state, you need to tell React to re-render; reassigning a variable, by itself, doesn't have side effects. You need to call the state setter to update React's internal state and then re-render with the new state.
So, you need
setCount(count + 1);
and not
count++;
because only the former will result in a re-render (even if you had declared count with let).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With