using-kea-disposables
БесплатноБез исполняемых скриптовНе проверенUse when adding timers (`setInterval`, `setTimeout`), event listeners (`window.addEventListener`, `document.addEventListener`…
от PostHog★ 41 278 звёзд на GitHubОб этом скилле
Using kea disposables
Every kea logic in this repo has cache.disposables injected by disposablesPlugin from the kea-disposables package, registered globally in frontend/src/initKea.ts and in frontend/src/toolbar/floating/index.tsx. Reach for it whenever you create a resource that needs explicit teardown — the plugin runs cleanup on unmount and automatically pauses background work when the tab is hidden.
The package is maintained outside this repo, so a change to the plugin itself belongs there, not here. Types come from the package too: import type { DisposablesManager } from 'kea-disposables'.
Do not add a beforeUnmount for cleanup. The plugin runs the cleanup function you return from setup automatically when the logic unmounts (and re-runs setup/cleanup around tab visibility changes). If you find yourself writing a beforeUnmount whose only job is to clearInterval / clearTimeout / removeEventListener something registered earlier in the same logic, register that resource through cache.disposables.add(...) instead and delete the beforeUnmount. Reserve beforeUnmount for teardown that isn't a resource you control (e.g. flushing state, persisting to localStorage, calling a third-party dispose()).
Use this skill when
- Adding
setIntervalorsetTimeoutinsideafterMount, a listener, or a subscription - Adding
window.addEventListener,document.addEventListener, orMediaQueryList.addEventListener - Adding any subscription that needs explicit teardown (WebSocket, EventSource, ResizeObserver, IntersectionObserver, etc.)
- Reviewing or editing a logic with a bare
cache.<thing>plus a matchingbeforeUnmountcleanup — convert it - A state change should tear down a previously-registered timer or listener early
The pattern
cache.disposables.add(
setup, // () => () => void — runs immediately; MUST return a cleanup function
key?, // string — re-adding with the same key disposes the previous one first
options?, // { pauseOnPageHidden?: boolean } — default true: cleanup runs on hide, setup re-runs on show
)
Canonical example (frontend/src/layout/navigation/noEventsBannerLogic.ts:14-21):
afterMount(({ actions, cache }) => {
cache.disposables.add(() => {
const pollTimer = window.setInterval(() => {
actions.loadCurrentTeam()
}, POLL_INTERVAL_MS)
return () => clearInterval(pollTimer)
})
}),
For a resource that lives exactly as long as the logic, the disposables builder replaces that afterMount:
import { disposables } from 'kea-disposables'
disposables(({ actions }) => ({
pollTimer: () => {
const id = window.setInterval(() => actions.loadCurrentTeam(), POLL_INTERVAL_MS)
return () => clearInterval(id)
},
})),
The object keys are ordinary disposable keys, so dispose('pollTimer') still stops it early.
Pass { setup, options } instead of a bare function to set pauseOnPageHidden.
Anything conditional, or re-armed from a listener, still wants cache.disposables.add(...).
Choosing a key
- No key — fire-and-forget; cleaned up only on unmount. Fine for one-shot listeners registered in
afterMount. - Named key — needed when:
- You'll call
cache.disposables.dispose(key)later to stop it early - The same setup may be re-added and each call should replace the previous one (spam-replacement)
- You'll call
pauseOnPageHidden
The default (true) is correct for almost everything — polling, animation tickers, hover timers. Background tabs stop doing work and resume on focus, which dramatically reduces CPU and network cost.
Opt out ({ pauseOnPageHidden: false }) only when the listener must keep firing while the page is hidden:
- Listeners for events that can genuinely fire while the tab is hidden — e.g.
storage(writes from another tab),online/offline,message(from web workers, service workers, or other windows) - A
visibilitychangelistener itself — the whole point is to observe hide/show - Anything the user expects to keep running while the tab is hidden
Note: popstate cannot fire on a hidden tab (it's user-driven), so pausing on hide is fine — see the toolbar example below.
Calling dispose() to stop early
cache.disposables.dispose('key') tears down one specific resource without unmounting the logic. Use it when a state transition should end the resource — pause/resume a poller, stop a hover-only ticker on mouseleave, close a modal-scoped listener.
Calling into the manager after unmount
add() and dispose() are no-ops once the logic has unmounted, so call them plainly.
Don't write cache.disposables?.dispose(...) or if (!cache.disposables) return; the manager is never null after mount.
An async continuation usually has to skip more than the disposable, though, because dispatching an action or reading values on a torn-down logic is its own bug.
Br
Установить using-kea-disposables в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл using-kea-disposables?
Use when adding timers (`setInterval`, `setTimeout`), event listeners (`window.addEventListener`, `document.addEventListener`, `MediaQueryList.addEventListener`), or any other resource that needs cleanup inside a kea logic. Every logic has `cache.disposables.add(setup, key?, options?)` and `cache.disposables.dispose(key)` available via the globally registered `disposablesPlugin` from the `kea-disposables` package. Replaces the bare `cache.foo = setInterval(...)` + `beforeUnmount: clearInterval(cache.foo)` pattern and auto-pauses background work when the tab is hidden.
Как установить скилл using-kea-disposables?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл using-kea-disposables запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic