Home > Software engineering >  Why do we need to use setValue in UseState?
Why do we need to use setValue in UseState?

Time:11-06

So, React has UseState hook, and we should use it like this.

const [value, setValue] = useState(0);

And if we want to change a value, it should be written like this:

const increase = () => {
setValue(value   1)
}

Why it's not possible to write it like this? Why we need setValue?

const increase = () => {
return value   1;
}

I understand that it just doesn't work, but I couldn't find an explanation why it is like that.

CodePudding user response:

The useState hook returns a function to update the state. Using setValue(value) method, you can get the previous(or old) state value to update the state.

On the other hand, without useState when you tries to increment the value, the value will not change because the react rendered the component only once and since there is no state change it won't get re-rendered, the value will remain at 0. You can see here in details : https://dev.to/aasthapandey/why-to-use-usestate-in-react-pkf

CodePudding user response:

Answer is simple...! The state variable is directly linked to rendering your page. The state variable of useState hook is read only for the component to render it in the below return statement which renders the JSX.

The setValue() function not only changes the state value, but will also trigger the react to re-render the DOM which has already being painted on the browser.

Well that's a difference between an ordinary HTML page & a React App. React provides amazing framework to re-render the page automatically after the you alter the state using the setValue() fucntion

  • Related