| 1 | --- |
| 2 | title: Do Not Put Effect Events in Dependency Arrays |
| 3 | impact: LOW |
| 4 | impactDescription: avoids unnecessary effect re-runs and lint errors |
| 5 | tags: advanced, hooks, useEffectEvent, dependencies, effects |
| 6 | --- |
| 7 | |
| 8 | ## Do Not Put Effect Events in Dependency Arrays |
| 9 | |
| 10 | Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect. |
| 11 | |
| 12 | **Incorrect (Effect Event added as a dependency):** |
| 13 | |
| 14 | ```tsx |
| 15 | import { useEffect, useEffectEvent |
| 16 | |
| 17 | function ChatRoom({ roomId |
| 18 | const handleConnected = |
| 19 | |
| 20 | useEffect(() => |
| 21 | const connection = |
| 22 | connection.on("connected |
| 23 | connection.connect(); |
| 24 | |
| 25 | return () => |
| 26 | }, [roomId, |
| 27 | } |
| 28 | ``` |
| 29 | |
| 30 | Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule. |
| 31 | |
| 32 | **Correct (depend on reactive values, not the Effect Event):** |
| 33 | |
| 34 | ```tsx |
| 35 | import { useEffect, useEffectEvent |
| 36 | |
| 37 | function ChatRoom({ roomId |
| 38 | const handleConnected = |
| 39 | |
| 40 | useEffect(() => |
| 41 | const connection = |
| 42 | connection.on("connected |
| 43 | connection.connect(); |
| 44 | |
| 45 | return () => |
| 46 | }, [roomId]); |
| 47 | } |
| 48 | ``` |
| 49 | |
| 50 | Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps |