Claude Code 101
← All lessons
Lesson 12Claude Code 101

Hooks in Claude Code

Summary audio

Spoken summary — press play to read along: the line being spoken stays near the top.

Study notes

What Are Hooks?

  • Deterministic execution: Hooks always run, unlike prompt instructions which may not
  • Run commands at specific points in Claude's lifecycle

Hook Events

  • User prompt submit: Runs when you submit a prompt (before Claude processes it)
  • Pre-tool use: Runs before a tool call executes
  • Post-tool use: Runs after a tool call completes
  • Notification: Runs when Claude sends a notification
  • Stop: Runs when Claude finishes responding

Common Use Cases

  • Auto-formatting files after edits
  • Logging executed commands for compliance
  • Blocking dangerous operations (e. g. , modifying production files)
  • Sending notifications when tasks complete

Configuration

  • Configured in settings. json file
  • Specify: event type, optional matcher (which tools apply), and command to run
  • Project-level hooks can be checked into your repo for team-wide consistency

Pre-Tool Use Hooks (Blocking Operations)

  • Receive tool name and input as JSON on stdin
  • Exit code 0 = proceed
  • Exit code 2 = block the action
  • Error message sent to Claude as feedback explaining why it was blocked

Best Practices

  • Use post-tool use for auto-formatting and logging
  • Use pre-tool use to enforce hard rules and block dangerous operations
  • Use CLAUDE_PROJECT_DIR environment variable in commands to reference project scripts
  • If something must happen every time without fail, use a hook instead of a prompt

Takeaways

  • Hooks guarantee execution at specific lifecycle points, unlike prompt instructions which may be skipped—use them when something must always happen
  • Pre-tool use hooks can block operations by returning exit code 2, making them ideal for enforcing safety rules (e. g. , preventing production file modifications)
  • Post-tool use hooks are for automation: auto-formatting, logging, and notifications that should run after tool execution completes
  • **Configure hooks in settings. json** with event type, optional tool matcher, and command; project-level hooks can be version-controlled for team consistency
  • Use exit codes strategically: exit 0 to proceed, exit 2 to block, with error messages sent to Claude explaining the rejection
Flashcards 10 cards
Question
click to reveal · ←/→
Answer
click to flip back
Export to Anki (.tsv) ↓
Knowledge check 6 questions