PreCompact and PostCompact Hooks - Claude Code
Fire before and after context compaction.
PreCompact and PostCompact hooks let you control or observe when Claude compacts context to stay within the window.
What it does
PreCompact fires just before Claude summarizes older turns. It can block the compaction, customize the summary strategy, or persist important context before it gets condensed. PostCompact fires after compaction completes, receiving the before/after sizes and the summary used. It's the clean hook point for "make sure this important decision survives compaction".
When to use it
- Snapshotting state to disk before a compaction you're worried about.
- Injecting explicit "keep this" notes before summarization.
- Measuring compaction frequency for context-efficiency tuning.
- Auditing what the summarizer is choosing to forget.
Gotchas
- Aggressive PreCompact logic can delay long turns noticeably.
- Custom compaction strategies are powerful and easy to get wrong. Start with the default.
- PostCompact runs with the new, smaller context. The hook can't reference what was dropped.
Official docs: https://code.claude.com/docs/en/hooks.md#precompact
Technical content at the intersection of AI and development. Building with AI agents, Claude Code, and modern dev tools - then showing you exactly how it works.
Get the weekly deep dive
Tutorials on Claude Code, AI agents, and dev tools - delivered free every week.
Was this helpful?




