6 ms·
Ask HN: How come, const variable can be modified in react
I can modify const variable in react using setSate but not in vanilljs. Any reason ?
- detaro 4y agoIt's very unclear what you mean, but I suspect the answer is something along the lines of "you are not modifying the variable, you are creating a new one with the same name"
- IceMetalPunk 4y agoWhen you have something like `const [variable, setVariable] = setState('foobar')`, you are not getting "variable" back directly. Instead, you're getting a pair of a setter function and a getter function. React keeps track of the variable's value internally, and when you access `variable` you're really just calling a getter function that "requests" the value from React, essentially. So you can can call `setVariable` to modify the value internally to React without actually changing the binding of the variable you see, hence it can be const.
- dee8717 4y agoThanks, that makes some sense.