This is a broader question about the use of different variable declarations in react native functional components (as opposed to class components), specially the use of let vs const, and how they are effected by renders and such. For this question, when I say 'render' or 're-render' I am talking about the execution of the render function (like 'MyFunctionalComponent' below), not necessarily a UI update/change.
From my understanding, unlike plain js, a const variable is not exactly 'constant' in react/react native, and can be changed (with hooks?) like so:
export default function MyFunctionalComponent() {
const [test, setTest] = useState(false);
const testFunction = () => { //some sort of function, maybe called by a button press
setTest(true); //this can change test, but something like 'test = true' throws an error
}
}
However let can take on similar behavior from my understanding:
export default function MyFunctionalComponent() {
let test = false
const testFunction = () => { //some sort of function, maybe called by a button press
test = true;
}
}
However, most react native examples and tutorials and such I have looked at, always seem to use the const syntax, even though it seems to involve much more code. Why? Personal preference, or necessity? Does the const way of doing things somehow re-render/re-call MyFunctionalComponent with a new value for the const variable?
Next, I'm not sure the exact behavior that is causing this, but sometimes when using the const syntax inside the functional component, the variables change and save state between render calls, and sometimes, a const variable is reset to its default state every time the render is called. (I know this part is vague, so feel free to ignore it if there is not enough detail) Why does this happen?
Similarly, I have seen different behavior when consts are created outside of the functional component instead of within... does scope work as you would expect with these? Are they (still?) re-instantiated on new render calls? Does 'setState' call an re-render? Shortening the previous question, why do some of my const's preserve their state on re-renders, while some seem to reset to their defaults?
Where does var fall into this, does it act the same as in regular js, or is it affected by react as well? (I feel like I have a grasp of the differences in these variable declarations in regular js, but this const behavior with react making me question it all).
So overall the question is basically, what are the differences/advantages of let, var, and const, specifically in react/react native, and how do those differ from regular javascript?
Lastly, does it differ between class components and functional components in react native?
Thank you for reading this long question.