How does useState change even when it's a const?
Asked Answered
S

3

12

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.

Seifert answered 28/9, 2022 at 8:48 Comment(0)
Z
11
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.

Zinc answered 29/9, 2022 at 18:18 Comment(0)
A
1

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.

Auerbach answered 28/9, 2022 at 10:33 Comment(1)
So the const is actually being variable shadowed aswell by useState()?Seifert
A
1

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.

Alon answered 29/9, 2022 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.