does value1 & value2 & func1 & func2 reassign to memory?
in short the answer is yes.
it's more clear if you look at it for what it is: Test
is a function, so everytime that function is called all the variables inside the function scope (the curly brackets) are re-declared and re-assigned.
Let's dive into the details:
value1
and func1
are in the function's body so they get declared and assigned every time the function is called, they are not related at all, they have just the same name.
value2
and func2
instead are declared inside an useEffect hook with a declared dependency (sth
), this means that these 2 variables are redeclared and reassigned only after the first render and after every other render if the sth
variable changed its value compared to the previous render.
if you want to optimize value1
so it doesn't change at every render you can use the useMemo
hook this way:
const value1 = React.useMemo(() => {
return "test1"; //here you might have a more complicate way to determine value1
}, []); //array of dependencies like for `useEffect`, so `value1` will be recalculated only if any of the values provided in here change. by leaving it empty value1 will always be the **same** variable
you can do similar optimizations with functions too with the useCallback
hook