| 1 | --- |
| 2 | title: Split Combined Hook Computations |
| 3 | impact: MEDIUM |
| 4 | impactDescription: avoids recomputing independent steps |
| 5 | tags: rerender, useMemo, useEffect, dependencies, optimization |
| 6 | --- |
| 7 | |
| 8 | ## Split Combined Hook Computations |
| 9 | |
| 10 | When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value. |
| 11 | |
| 12 | **Incorrect (changing `sortOrder |
| 13 | |
| 14 | ```tsx |
| 15 | const sortedProducts = useMemo |
| 16 | const filtered = |
| 17 | const sorted = |
| 18 | sortOrder === "asc" |
| 19 | ); |
| 20 | return sorted; |
| 21 | }, [products, category |
| 22 | ``` |
| 23 | |
| 24 | **Correct (filtering only recomputes when products or category change):** |
| 25 | |
| 26 | ```tsx |
| 27 | const filteredProducts = useMemo |
| 28 | () => products. |
| 29 | [products, category] |
| 30 | ); |
| 31 | |
| 32 | const sortedProducts = useMemo |
| 33 | () => |
| 34 | filteredProducts.toSorted((a |
| 35 | sortOrder === "asc" |
| 36 | ), |
| 37 | [filteredProducts, sortOrder] |
| 38 | ); |
| 39 | ``` |
| 40 | |
| 41 | This pattern also applies to `useEffect` when combining unrelated side effects: |
| 42 | |
| 43 | **Incorrect (both effects run when either dependency changes):** |
| 44 | |
| 45 | ```tsx |
| 46 | useEffect(() => { |
| 47 | analytics.trackPageView(pathname |
| 48 | document.title = |
| 49 | }, [pathname, pageTitle |
| 50 | ``` |
| 51 | |
| 52 | **Correct (effects run independently):** |
| 53 | |
| 54 | ```tsx |
| 55 | useEffect(() => { |
| 56 | analytics.trackPageView(pathname |
| 57 | }, [pathname]); |
| 58 | |
| 59 | useEffect(() => { |
| 60 | document.title = |
| 61 | }, [pageTitle]); |
| 62 | ``` |
| 63 | |
| 64 | **Note:** If your project has [React Compiler |