Skip to main content
rule CX Codex

client-event-listeners — Claude Code rule

client-event-listeners — a Claude rule that keeps a single keydown listener on window no matter how many components call the shortcut hook.

MIT ★ 7,191 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/client-event-listeners.md
Open on GitHub

What client-event-listeners does

The rule targets a familiar React leak. A custom hook such as useKeyboardShortcut attaches a keydown handler to window inside useEffect, so every component that calls it adds another listener. Ten call sites, ten handlers doing the same work.

The file shows both versions. The bad one is that per-instance useEffect. The fixed one keeps a module-level Map from key to a set of callbacks and opens a single useSWRSubscription('global-keydown', ...) that fans the event out. On unmount the callback leaves the set, and an empty key drops out of the Map.

The import comes from swr/subscription, so swr has to be in the project already. The header marks this rule as LOW impact, which fits: it trims listener overhead, it does not change how data flows.

What it helps with

  • strip duplicate keydown handlers when several components subscribe
  • collapse N window listeners into one for the whole app
  • move a shortcut hook onto useSWRSubscription
  • clean up callbacks in the module-level Map on unmount
  • explain in review why a per-instance useEffect listener hurts

Example prompts for the agent

  • Rewrite useKeyboardShortcut so the app registers one keydown listener on window, not one per component.
  • Find global subscriptions in this project and dedupe them with useSWRSubscription.
  • Why does Profile end up with several keydown handlers, and how do I collapse them into one?

How to install client-event-listeners

Manually: put the files in place

.claude/rules/client-event-listeners.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about client-event-listeners

How do I install client-event-listeners in Claude Code?

Add the rule file at .claude/rules/client-event-listeners.md in your project, taking the text from the tech-leads-club/agent-skills repository.

What does client-event-listeners do?

It shows how to swap per-component global listeners for one shared subscription, built on a module-level callback Map and useSWRSubscription.

What does the example need in order to work?

The swr package, because the import is swr/subscription.

Source text

client-event-listeners.md · MIT
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---

## Deduplicate Global Event Listeners

Use `useSWRSubscription()` to share global event listeners across component instances.

**Incorrect (N instances = N listeners):**

```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.metaKey && e.key === key) {
        callback()
      }
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [key, callback])
}
```

When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.

**Correct (N instances = 1 listener):**

```tsx
import useSWRSubscription from 'swr/subscription'

// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()

function useKeyboardShortcut(key: string, callback: () => void) {
  // Register this callback in the Map
  useEffect(() => {
    if (!keyCallbacks.has(key)) {
      keyCallbacks.set(key, new Set())
    }
    keyCallbacks.get(key)!.add(callback)

    return () => {
      const set = keyCallbacks.get(key)
      if (set) {
        set.delete(callback)
        if (set.size === 0) {
          keyCallbacks.delete(key)
        }
      }
    }
  }, [key, callback])

  useSWRSubscription('global-keydown', () => {
    const handler = (e: KeyboardEvent) => {
      if (e.metaKey && keyCallbacks.has(e.key)) {
        keyCallbacks.get(e.key)!.forEach(cb => cb())
      }
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  })
}

function Profile() {
  // Multiple shortcuts will share the same listener
  useKeyboardShortcut('p', () => { /* ... */ }) 
  useKeyboardShortcut('k', () => { /* ... */ })
  // ...
}
```

© tech-leads-club · MIT · tech-leads-club/agent-skills

Similar IDE rules

All IDE rules for Frontend and UI →

From the same set130

The whole set →
js-tosorted-immutable The js-tosorted-immutable rule replaces mutating .sort() with .toSorted(), keeping React props and state arrays unchanged during sorting. CX Codex +1 ★ 7,191repo stars patterns-children-over-render-props patterns-children-over-render-props — a Claude rule that pushes React components toward composition with children instead of renderX props, so call sites read as plain JSX. CX Codex +1 ★ 7,191repo stars js-cache-function-results js-cache-function-results instructs the agent to cache repeated function calls using a module-level Map. It eliminates redundant computations across renders and utility calls. CX Codex +1 ★ 7,191repo stars client-localstorage-schema The client-localstorage-schema rule guides Claude Code to version localStorage keys and keep only fields the UI needs. Use it when changing client-side settings or cached user data. CX Codex +1 ★ 7,191repo stars server-after-nonblocking server-after-nonblocking instructs the agent to schedule logging, analytics, and cleanup with Next.js after(). This sends responses right away without waiting for background work. CX Codex +1 ★ 7,191repo stars rerender-lazy-state-init The rerender-lazy-state-init rule recommends lazy useState initialization for costly starting values. It helps when a React component reads stored settings or builds a data structure. CX Codex +1 ★ 7,191repo stars async-defer-await async-defer-await — a rule that moves await operations into code branches where they're actually needed, preventing blockage of execution paths that may exit early. CX Codex +1 ★ 7,191repo stars server-dedup-props server-dedup-props — a rule for Claude Code about React Server Components: RSC-to-client serialization deduplicates by reference, not value. Server-side transforms like toSorted or filter create new references and double the payload. CX Codex +1 ★ 7,191repo stars

Project sponsors

Companies that keep this analytics open