writing-kea-logics
Skill721 starsChanged 2 months agoMITView on GitHub
Guide for writing or reviewing PostHog kea logic files (`*Logic.ts` / `*Logic.tsx`). Use when creating a new logic, adding actions/reducers/selectors/listeners/loaders/forms/router bindings, choosing between reducer vs selector vs cache, deciding between listeners and `kea-subscriptions`, wiring React with `useValues`/`useActions`/`BindLogic`, or onboarding to kea conventions. Read keajs.org for upstream API; this skill captures PostHog-specific conventions and idioms.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- PostHog/posthogword for word, first seen Oct 4, 2026
Other versions1 project uses a version of this.
Word for word · 1
- PostHog/posthog★ 40k100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository119 other files it gives its agents.
- AGENTS.mdAGENTS.md
- common/AGENTS.mdAGENTS.md
- proto/AGENTS.mdAGENTS.md
- rust/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- common/CLAUDE.mdCLAUDE.md
- proto/CLAUDE.mdCLAUDE.md
- rust/CLAUDE.mdCLAUDE.md
- .cursor/rules/django-python.mdcCursor rule
- .cursor/rules/react-typescript.mdcCursor rule
- .cursor/rules/rust.mdcCursor rule
- adding-activity-loggingSkill
- adding-api-scopesSkill
- adding-inbound-webhooksSkill
- adding-inbox-sourcesSkill
- adding-ingestion-warningsSkill
- adding-mcp-store-serversSkill
- adding-personhog-rpcSkill
- adding-product-alertingSkill
- adding-project-secret-api-key-authSkill
- adopting-generated-api-typesSkill
- analyzing-experiment-precompute-canarySkill
- analyzing-experiment-query-performanceSkill
- analyzing-insights-across-teamsSkill
- announcing-behavior-changesSkill
- auditing-llm-gateway-paritySkill
- auditing-warehouse-source-coverageSkill
- authenticating-to-clickhouseSkill
- authoring-ci-workflowsSkill
- autoresolving-pr-conflictsSkill
- building-product-empty-statesSkill
- clickhouse-migrationsSkill
- debugging-ci-failuresSkill
- debugging-local-replaySkill
- debugging-local-task-agent-runsSkill
- debugging-mcp-analyticsSkill
- debugging-signals-pipelineSkill
- debugging-table-access-deniedSkill
- depot-ciSkill
- depot-container-buildsSkill
- depot-github-runnersSkill
- developing-subscriptionsSkill
- django-migrationsSkill
- django-startup-timeSkill
- documenting-warehouse-sourcesSkill
- editing-agents-mdSkill
- establishing-code-ownershipSkill
- extending-hobby-smoke-testsSkill
- extending-personhog-test-harnessSkill
- finding-llm-gateway-migration-candidatesSkill
- fixing-flaky-testsSkill
- gating-production-deploysSkill
- gating-sensitive-actionsSkill
- generating-clickhouse-query-performance-reportsSkill
- hogliSkill
- implementing-mcp-toolsSkill
- implementing-mcp-ui-appsSkill
- implementing-warehouse-sourcesSkill
- improving-drf-endpointsSkill
- improving-mcp-toolsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 5 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 15
When in doubt about whether to use it, read here.
- Distinctive: line 31
If your work overlaps it, read the companion skill first.
- Very specific: line 47
Generated types are the contract: Every logic has an inline generated MakeLogicType block above its kea() call.
- Distinctive: line 113
Does it come from an HTTP call?: Use a loader.
- Very specific: line 114
Can it be computed from other state?: Use a selector.
- Very specific: line 117
Is it a timer, listener, or other disposable resource?: Use cache.disposables — see using-kea-disposables.
- Very specific: line 179
Use this loop while writing the logic.
- Very specific: line 183
Do not create or import a separate *LogicType.ts file.
- Distinctive: line 191
Read the relevant reference above before inventing a new pattern.
- Distinctive: line 192
Read the upstream keajs.org docs for builder signatures.
- Very specific: line 193
Search the repo for the builder name in *Logic.ts — there are hundreds of working examples and the conventions are stable.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Writing kea logics
PostHog uses kea as the state container for the frontend. Almost
all non-trivial business logic lives in a *Logic.ts / *Logic.tsx file, not in
React. We may be on a kea pre-release ahead of the version the keajs.org docs
cover — when in doubt, check pnpm-workspace.yaml for the pinned version.
This skill captures the PostHog-specific conventions on top of the upstream kea docs. When in doubt about a builder's signature, go upstream. When in doubt about whether to use it, read here.
Use this skill when
- Creating a new
*Logic.ts/*Logic.tsxfile - Adding builders to an existing logic (actions, reducers, selectors, listeners, loaders, forms)
- Choosing between
reducervsselectorvscachevsloaderfor a piece of state - Wiring a React component to a logic
- Reviewing a PR that introduces or modifies a kea logic
- Reviewing code that uses React hooks where a logic would be more idiomatic
Companion skills (do not duplicate)
- using-kea-disposables —
setInterval,addEventListener, and any other resource that needs cleanup.
If your work overlaps it, read the companion skill first.
Core principles
- Business logic lives in a logic, not in a component. CLAUDE.md is explicit: "If there is a kea logic file, write all business logic there, avoid React hooks at all costs." Hooks are for view concerns.
- One concept, one source of truth. Pick exactly one of: action-driven reducer, derived selector, async loader. Don't mirror the same value into multiple places.
- Prefer listeners over
kea-subscriptions. Subscriptions install a redux subscription that re-runs on every dispatch and is measurably slower. Listen to the action that changed the value instead. See references/reacting-to-changes.md. - Generated types are the contract. Every logic has an inline generated
MakeLogicTypeblock above itskea()call. Import a logic type from the logic source file, never from a separate*LogicType.tsfile. - Resources that need cleanup go through
cache.disposables. See the using-kea-disposables skill.
Anatomy at a glance
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import * as api from 'products/foo/frontend/generated/api'
export interface FooLogicProps {
fooId: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface fooLogicValues {
name: string
nameUpper: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface fooLogicActions {
setName: (name: string) => { name: string }
}
export type fooLogicType = MakeLogicType<fooLogicValues, fooLogicActions, FooLogicProps>
export const fooLogic = kea<fooLogicType>([
props({} as FooLogicProps),
key((props) => props.fooId),
path((key) => ['scenes', 'foo', 'fooLogic', key]),
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
actions({ setName: (name: string) => ({ name }) }),
loaders(({ props }) => ({
foo: [null as Foo | null, { loadFoo: async () => api.foosRetrieve(props.fooId) }],
})),
reducers({ name: ['', { setName: (_, { name }) => name }] }),
selectors({ nameUpper: [(s) => [s.name], (name): string => name.toUpperCase()] }),
listeners(({ actions }) => ({
loadFooSuccess: () => {
/* ... */
},
})),
afterMount(({ actions }) => {
actions.loadFoo()
}),
])Conventional block order: props → key → path → connect → actions → forms → loaders →
reducers → selectors → sharedListeners → listeners → subscriptions (rare) →
windowValues → urlToAction / actionToUrl → afterMount / propsChanged / beforeUnmount.
You almost never need all of those — half a dozen blocks is typical. Pick the ones the logic actually uses and leave the rest out.
Decision flow — pick the right container before you start
Most kea bugs come from picking the wrong container for a piece of state. Work through this before reaching for any builder:
- Does it come from an HTTP call? Use a loader.
- Can it be computed from other state? Use a
selector. - Does an action change it, and does the UI need to re-render when it changes?
Use a
reducer. - Is it a timer, listener, or other disposable resource? Use
cache.disposables— see using-kea-disposables.
cache.foo is an escape hatch for transient flags the UI never reads — reach for it
last, not first. See references/state-decision.md
for the full breakdown.
Pattern index
Each reference covers one job-to-be-done with the pattern shape, why it's the right shape, and the trade-offs. File citations inside references are "examples in the wild today" — they age, so the pattern itself is the source of truth.
| You want to... | Read |
| Decide between reducer / selector / cache / loader | references/state-decision.md |
| Load data from the API | references/loading-data.md |
| Poll an endpoint or refresh on an interval | references/polling.md |
| Build a form | references/forms.md |
| Sync state with the URL | references/routing.md |
| Persist state across reloads | references/persisting-state.md |
| React to a value change | references/reacting-to-changes.md |
| Have multiple instances of one logic | references/keyed-logics.md |
| Share state across logics or a component subtree | references/connecting-logics.md |
| Test the logic | references/testing.md |
| Recognise a pattern you should convert on sight | references/anti-patterns.md |
Types and typegen
import { MakeLogicType, kea } from 'kea'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface fooLogicValues {
name: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface fooLogicActions {
setName: (name: string) => { name: string }
}
export type fooLogicType = MakeLogicType<fooLogicValues, fooLogicActions>
export const fooLogic = kea<fooLogicType>([...])Inline type blocks are produced by kea-typegen 3.8.3. Commands:
pnpm --filter=@posthog/frontend typegen:watch— watch mode while writing logicspnpm --filter=@posthog/frontend typegen:write— one-shot writepnpm --filter=@posthog/frontend typegen:check— CI parity check
Iterating on one logic
Full typegen over the whole codebase is slow. When you're iterating on a single logic, scope typegen to that file:
# Regenerate the type for one logic
pnpm --filter=@posthog/frontend typegen:file frontend/src/scenes/foo/fooLogic.tsUse this loop while writing the logic. The current tsgo does not support combining
the project config with a file argument, so run the full typegen:check and
typescript:check once at the end to confirm nothing else broke.
Do not create or import a separate *LogicType.ts file. Change the logic and re-run
typegen so the inline generated block stays authoritative.
For keyed logics, annotate the export explicitly:
export const fooLogic: LogicWrapper<fooLogicType> = kea<fooLogicType>([...]).
When in doubt
- Read the relevant reference above before inventing a new pattern.
- Read the upstream keajs.org docs for builder signatures.
- Search the repo for the builder name in
*Logic.ts— there are hundreds of working examples and the conventions are stable. - For state-management decisions, favour the option that lets you delete code elsewhere.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

