The useEffect
and setState
will cause extra renders on every change: the first render will “lag behind” with stale data and then it’ll immediately queue up an additional render with the new data.
Suppose we have:
// Maybe I'm running this on a literal potato
function expensiveCalculation(x) { return x + 1; };
Lets suppose x
is initially 0:
- The
useMemo
version immediately renders1
. - The
useEffect
version rendersnull
, then after the component renders the effect runs, changes the state, and queues up a new render with1
.
Then if we change x
to 2:
- The
useMemo
runs and3
is rendered. - The
useEffect
version runs, and renders1
again, then the effect triggers and the component reruns with the correct value of3
.
In terms of how often expensiveCalculation
runs, the two have identical behavior, but the useEffect
version is causing twice as much rendering which is bad for performance for other reasons.
Plus, the useMemo
version is just cleaner and more readable, IMO. It doesn’t introduce unnecessary mutable state and has fewer moving parts.
So you’re better off just using useMemo
here.