| 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 } from 'react' |
| 16 | |
| 17 | function ChatRoom({ roomId, onConnected }: { |
| 18 | roomId: string |
| 19 | onConnected: () => void |
| 20 | }) { |
| 21 | const handleConnected = useEffectEvent(onConnected) |
| 22 | |
| 23 | useEffect(() => { |
| 24 | const connection = createConnection(roomId) |
| 25 | connection.on('connected', handleConnected) |
| 26 | connection.connect() |
| 27 | |
| 28 | return () => connection.disconnect() |
| 29 | }, [roomId, handleConnected]) |
| 30 | } |
| 31 | ``` |
| 32 | |
| 33 | Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule. |
| 34 | |
| 35 | **Correct (depend on reactive values, not the Effect Event):** |
| 36 | |
| 37 | ```tsx |
| 38 | import { useEffect, useEffectEvent } from 'react' |
| 39 | |
| 40 | function ChatRoom({ roomId, onConnected }: { |
| 41 | roomId: string |
| 42 | onConnected: () => void |
| 43 | }) { |
| 44 | const handleConnected = useEffectEvent(onConnected) |
| 45 | |
| 46 | useEffect(() => { |
| 47 | const connection = createConnection(roomId) |
| 48 | connection.on('connected', handleConnected) |
| 49 | connection.connect() |
| 50 | |
| 51 | return () => connection.disconnect() |
| 52 | }, [roomId]) |
| 53 | } |
| 54 | ``` |
| 55 | |
| 56 | Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps) |
| 57 |