Search⌘ K
AI Features

Hooks and Automated Behaviors

Explore how to use hooks in Claude Code for automating behaviors during an agent's lifecycle. Understand the five hook events, write hook configurations, and apply exit code protocols to control tool executions and task notifications. Distinguish when to use hooks versus dispatch_tool guards for production-ready AI systems.

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 PreToolUse hooks and how it blocks tool calls.

  • Distinguish the appropriate use cases for hooks vs. dispatch_tool guards.

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

PreToolUse

Before any tool call executes

PostToolUse

After a tool call completes

Stop

When Claude finishes a turn (end_turn or stop_sequence)

PreCompact

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.

Hook configuration

Hooks are ...