| 1 | --- |
| 2 | title: Do not wrap a simple expression with a primitive result type in useMemo |
| 3 | impact: LOW-MEDIUM |
| 4 | impactDescription: wasted computation on every render |
| 5 | tags: rerender, useMemo, optimization |
| 6 | --- |
| 7 | |
| 8 | ## Do not wrap a simple expression with a primitive result type in useMemo |
| 9 | |
| 10 | When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`. |
| 11 | Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself. |
| 12 | |
| 13 | **Incorrect:** |
| 14 | |
| 15 | ```tsx |
| 16 | function Header({ user |
| 17 | const isLoading = |
| 18 | return user.isLoading |
| 19 | }, [user.isLoading |
| 20 | |
| 21 | if (isLoading) return |
| 22 | // return some markup |
| 23 | } |
| 24 | ``` |
| 25 | |
| 26 | **Correct:** |
| 27 | |
| 28 | ```tsx |
| 29 | function Header({ user |
| 30 | const isLoading = |
| 31 | |
| 32 | if (isLoading) return |
| 33 | // return some markup |
| 34 | } |
| 35 | ``` |