const sum = useMemo(() => a + b, [a, b])
what will happen when a
and b
are interchanged. Like if a = 5
, b = 10
in the current render. What will happen when a = 10
, b = 5
? will it re-render after it is changed?
Not getting the consistent answer for this.
3
Answers
A re-render occurs whenever the state changes (among other things).
In your case, the value of
sum
will be recomputed if eithera
orb
changes. However, it won’t trigger a re-render of the component because it is not part of its state.Changing the value of
a
orb
will provoke a re-render because they are either part of the state of the component or are passed as props.It’s not a matter of
useMemo()
hook, as it is created to cache result of intensive calculations.The question here, as noticed Florent, is what is
a
andb
– are they props variables or state variables, or some other specific case.If it’s state or props – it will trigger re-render.
If this is special case like value of uncontrolled input or saved using
useRef()
, it will not trigger re-render.You are confusing rendering for computing.
No. The
useMemo
will never trigger a render.Having said that, the component will most likely re-render, because:
You changed the values of
a
andb
by updating the state. Calling the setter will trigger a component render.You changed the values of
a
andb
by mutating the component props. Changing props will also trigger a component render.So the change in
a
and/orb
will already have triggered a render.Your question is probably if
sum
will recompute during the render. To which the answer is yes. Ifa
and/orb
changes value theuseMemo
function is executed and the new value is calculated.In your provided scenario
sum
is the result of a commutative operation.a + b
produces the same result asb + a
. HoweveruseMemo
does not analyse the function passed and sees it as a black box. It does not know if the operation is commutative or not. Say you would have passeda - b
instead, then swapping thea
andb
values produces a different value. ThereforeuseMemo
has to recompute the result.An easy way to test this would be to add a
console.log()
inside theuseMemo
call.