Awesome follow-up! useMemo
can definitely help with performance—but only if used correctly. Let's break it down:
What
useMemo
Does
-
It memoizes (remembers) the result of a function.
-
Only recomputes when dependencies change.
-
Avoids unnecessary re-runs of expensive calculations on every render.
So, it helps with:
-
Heavy computations.
-
Avoiding re-renders of components when props haven't actually changed.
-
Stabilizing references (e.g. objects/arrays/functions) passed as props to children.
🧠 Common Use Cases
-
Calculating derived data from props or state.
-
Preventing re-renders when passing stable values to
useEffect
,React.memo
components, etc. -
Memoizing options/configs (e.g. chart settings, select dropdowns).
🚫 Common Mistakes
-
Using it prematurely ("premature optimization")
-
Don’t use
useMemo
just to avoid re-running simple logic. -
Example of overkill:
-
-
Ignoring dependencies
-
If your dependency array is incomplete, you'll get stale values.
-
-
Using it for side effects
-
useMemo
should be pure—no side effects like API calls or state updates. -
Use
useEffect
for that instead.
-
-
Expecting it to prevent re-renders
-
useMemo
memoizes a value, not a component. -
Use
React.memo
for memoizing components.
-
-
Stabilizing functions? Use
useCallback
-
If you're memoizing a function,
useCallback
is usually better:
-
✅ When It's Worth It
-
You're doing expensive calculations (e.g., filtering, sorting, large data sets).
-
You're passing objects/functions as props to children wrapped in
React.memo
. -
You're experiencing performance bottlenecks from unnecessary recalculations.