Home > other >  How does useState change even when it's a const?
How does useState change even when it's a const?

Time:09-30

I know that const can not be changed, how does declaring a const [counter, setCouter] = useState(); still be able to change the const counter even though it's a const?

I came across variable shadowing and variables inside different block scopes. But the const counter here works fine even though it's not in a different scope when you reassign it with setCounter.

CodePudding user response:

function MyComponent() {
    const [state, setState] = useState("");
    return <SomeJsx/>;
}

When you call setState, the constant state does not change. Instead, MyComponent is called again, with useState now returning the updated value. This value is assigned to the state constant but this is part of a different function invocation, so it's actually not the same constant.

CodePudding user response:

well according to my understanding, in javascript const means you cannot re assign value to a variable using assignment operator and this is true with react state since state is immutable in react. you always need setState function to change it.

CodePudding user response:

You cannot reassign const values in JavaScript and React doesn't do that either. What happens instead is each time the component is rendered, you get a new value and assign it to a new const variable. Components are functions that get called on rerenders, while React manages to handle unchanged and changed states so that resources are calculated economically. That is also the reason why class components can't use hooks, since classes aren't 'called' on every rerender.

  • Related