| 1 | --- |
| 2 | title: Store Event Handlers in Refs |
| 3 | impact: LOW |
| 4 | impactDescription: stable subscriptions |
| 5 | tags: advanced, hooks, refs, event-handlers, optimization |
| 6 | --- |
| 7 | |
| 8 | ## Store Event Handlers in Refs |
| 9 | |
| 10 | Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes. |
| 11 | |
| 12 | **Incorrect (re-subscribes on every render):** |
| 13 | |
| 14 | ```tsx |
| 15 | function useWindowEvent(event: |
| 16 | useEffect(() => |
| 17 | window.addEventListener(event |
| 18 | return () => |
| 19 | }, [event, |
| 20 | } |
| 21 | ``` |
| 22 | |
| 23 | **Correct (stable subscription):** |
| 24 | |
| 25 | ```tsx |
| 26 | function useWindowEvent(event: |
| 27 | const handlerRef = |
| 28 | useEffect(() => |
| 29 | handlerRef.current = |
| 30 | }, [handler]); |
| 31 | |
| 32 | useEffect(() => |
| 33 | const listener = |
| 34 | window.addEventListener(event |
| 35 | return () => |
| 36 | }, [event]); |
| 37 | } |
| 38 | ``` |
| 39 | |
| 40 | **Alternative: use `useEffectEvent |
| 41 | |
| 42 | ```tsx |
| 43 | import { useEffectEvent } |
| 44 | |
| 45 | function useWindowEvent(event: |
| 46 | const onEvent = |
| 47 | |
| 48 | useEffect(() => |
| 49 | window.addEventListener(event |
| 50 | return () => |
| 51 | }, [event]); |
| 52 | } |
| 53 | ``` |
| 54 | |
| 55 | `useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler. |