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