[SOLVED] Using const to declare useState function

Issue

This Content is from Stack Overflow. Question asked by chu-js

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>);}

useState

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



Solution

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:

  • It updates the internal state React has for that state value
  • It tells the component to re-render, so as to generate a new view based on the new updated state

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).


This Question was asked in StackOverflow by chu-js and Answered by CertainPerformance It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?