lockstep

Claude Code Hooks

Hooks are shell commands Claude Code runs at fixed points, like before a tool call or at session start. Unlike CLAUDE.md, they run whatever Claude decides.

Hooks are shell commands Claude Code runs automatically at specific points in its lifecycle. Per Anthropic's hooks guide, they give deterministic control: certain actions always happen, rather than relying on the model to choose them.

Why they matter

CLAUDE.md is context. Claude reads it and tries to follow it, with no guarantee. A hook runs regardless. That makes hooks the right tool for rules that must never be broken.

Common hooks

EventRunsTypical use
PreToolUseBefore a tool callBlock edits to protected paths; exit code 2 blocks the call
PostToolUseAfter a tool call succeedsRun a formatter after every edit
SessionStartWhen a session starts, or after compaction with the compact matcherAdd context; stdout is added to Claude's context

Hooks are configured in a settings file such as .claude/settings.json. Which settings file applies is explained in Claude Code settings.json. When a PreToolUse hook exits with code 2, Claude sees the message the hook wrote to stderr and can change its approach.

For a worked example that blocks edits to applied migrations, see why Claude Code ignores your CLAUDE.md. For six copy-paste hooks and a reference, see Claude Code hooks examples.

What are Claude Code hooks?
User-defined shell commands that Claude Code runs at specific points in its lifecycle, such as before a tool call, after a file edit, or when a session starts. They give deterministic control: the action happens whether or not the model chooses it.
How does a hook block an action?
A PreToolUse hook that exits with code 2 blocks the tool call, and what it writes to stderr is shown to Claude as the reason, so it can adjust its plan.
How do I re-inject context after compaction?
Add a SessionStart hook with the matcher compact. Whatever the command prints to stdout is added to Claude's context after each compaction.

Related