Hooks and Automated Behaviors
Explore how to implement hooks in Claude Code to automate behaviors during different agent lifecycle events. Understand the five hook events, configure them with matchers and shell commands, and learn how PreToolUse hooks can block tool calls safely. Distinguish when to use hooks versus dispatch_tool guards to manage tool interactions and enforce policies effectively.
A hook is a shell command that Claude Code runs in response to a specific event in the agent life cycle. Hooks are the right mechanism for behaviors that must happen every time an event fires, such as logging every file write, blocking specific shell patterns before Claude runs them, or notifying a Slack channel when Claude finishes a task. Like code-level guards in dispatch_tool, hooks operate deterministically. Unlike dispatch_tool guards, hooks are shell commands configured in settings files, not Python functions embedded in the agent code. By the end of this lesson, we will be able to:
Name the five hook events and when each fires.
Write a hook configuration entry in the settings file with a matcher and a command.
Explain the exit code protocol for
PreToolUsehooks and how it blocks tool calls.Distinguish the appropriate use cases for hooks vs.
dispatch_toolguards.
The five hook events
Each hook event fires at a distinct point in the Claude Code life cycle. Understanding which event fires when, and whether it can stop the action, is the foundation of hook design.
Event | When It Fires |
| Before any tool call executes |
| After a tool call completes |
| When Claude finishes a turn ( |
| Before Claude Code compresses the conversation history |
PreToolUse is the only event where a hook can prevent the action from occurring. For all other events, the hook runs after the fact and cannot reverse what happened.