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.memocomponents, etc. -
Memoizing options/configs (e.g. chart settings, select dropdowns).
🚫 Common Mistakes
-
Using it prematurely ("premature optimization")
-
Don’t use
useMemojust 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
-
useMemoshould be pure—no side effects like API calls or state updates. -
Use
useEffectfor that instead.
-
-
Expecting it to prevent re-renders
-
useMemomemoizes a value, not a component. -
Use
React.memofor memoizing components.
-
-
Stabilizing functions? Use
useCallback-
If you're memoizing a function,
useCallbackis 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.
