| 1 | --- |
| 2 | title: Don't Define Components Inside Components |
| 3 | impact: HIGH |
| 4 | impactDescription: prevents remount on every render |
| 5 | tags: rerender, components, remount, performance |
| 6 | --- |
| 7 | |
| 8 | ## Don't Define Components Inside Components |
| 9 | |
| 10 | **Impact: HIGH (prevents remount on every render)** |
| 11 | |
| 12 | Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM. |
| 13 | |
| 14 | A common reason developers do this is to access parent variables without passing props. Always pass props instead. |
| 15 | |
| 16 | **Incorrect (remounts on every render):** |
| 17 | |
| 18 | ```tsx |
| 19 | function UserProfile({ user |
| 20 | // Defined inside to access `theme` - BAD |
| 21 | const Avatar = |
| 22 | <img src={ |
| 23 | ); |
| 24 | |
| 25 | // Defined inside to access `user` - BAD |
| 26 | const Stats = |
| 27 | <div> |
| 28 | <span>{user. |
| 29 | <span>{user. |
| 30 | </div> |
| 31 | ); |
| 32 | |
| 33 | return ( |
| 34 | <div> |
| 35 | <Avatar /> |
| 36 | <Stats /> |
| 37 | </div> |
| 38 | ); |
| 39 | } |
| 40 | ``` |
| 41 | |
| 42 | Every time `UserProfile` renders, `Avatar` and ` |
| 43 | |
| 44 | **Correct (pass props instead):** |
| 45 | |
| 46 | ```tsx |
| 47 | function Avatar({ src |
| 48 | return <img src |
| 49 | } |
| 50 | |
| 51 | function Stats({ followers |
| 52 | return ( |
| 53 | <div> |
| 54 | <span>{followers} |
| 55 | <span>{posts} |
| 56 | </div> |
| 57 | ); |
| 58 | } |
| 59 | |
| 60 | function UserProfile({ user |
| 61 | return ( |
| 62 | <div> |
| 63 | <Avatar src= |
| 64 | <Stats followers= |
| 65 | </div> |
| 66 | ); |
| 67 | } |
| 68 | ``` |
| 69 | |
| 70 | **Symptoms of this bug:** |
| 71 | |
| 72 | - Input fields lose focus on every keystroke |
| 73 | - Animations restart unexpectedly |
| 74 | - `useEffect` cleanup/setup runs on every parent render |
| 75 | - Scroll position resets inside the component |