| 1 | --- |
| 2 | title: Narrow Effect Dependencies |
| 3 | impact: LOW |
| 4 | impactDescription: minimizes effect re-runs |
| 5 | tags: rerender, useEffect, dependencies, optimization |
| 6 | --- |
| 7 | |
| 8 | ## Narrow Effect Dependencies |
| 9 | |
| 10 | Specify primitive dependencies instead of objects to minimize effect re-runs. |
| 11 | |
| 12 | **Incorrect (re-runs on any user field change):** |
| 13 | |
| 14 | ```tsx |
| 15 | useEffect(() => { |
| 16 | console.log(user.id) |
| 17 | }, [user]) |
| 18 | ``` |
| 19 | |
| 20 | **Correct (re-runs only when id changes):** |
| 21 | |
| 22 | ```tsx |
| 23 | useEffect(() => { |
| 24 | console.log(user.id) |
| 25 | }, [user.id]) |
| 26 | ``` |
| 27 | |
| 28 | **For derived state, compute outside effect:** |
| 29 | |
| 30 | ```tsx |
| 31 | // Incorrect: runs on width=767, 766, 765... |
| 32 | useEffect(() => { |
| 33 | if (width < 768) { |
| 34 | enableMobileMode() |
| 35 | } |
| 36 | }, [width]) |
| 37 | |
| 38 | // Correct: runs only on boolean transition |
| 39 | const isMobile = width < 768 |
| 40 | useEffect(() => { |
| 41 | if (isMobile) { |
| 42 | enableMobileMode() |
| 43 | } |
| 44 | }, [isMobile]) |
| 45 | ``` |
| 46 |