Lesson completed!
-

Lesson 15 / 19 · Automation

Hooks

Max Techera
Next

Hooks

Hooks let you run custom scripts before or after Claude performs actions, enabling powerful automation.

What Are Hooks?

Hooks are scripts that execute at specific points:

  • PreToolUse - Before Claude uses a tool
  • PostToolUse - After Claude uses a tool
  • PreEdit - Before file modifications
  • PostEdit - After file modifications

Configuring Hooks

Add hooks to your settings:

{
  "hooks": {
    "PostEdit": {
      "command": "npm run lint:fix",
      "pattern": "**/*.ts"
    }
  }
}

Common Hook Patterns

Auto-format on Edit

{
  "hooks": {
    "PostEdit": {
      "command": "prettier --write",
      "pattern": "**/*.{ts,tsx,js,jsx}"
    }
  }
}

Auto-lint

{
  "hooks": {
    "PostEdit": {
      "command": "eslint --fix",
      "pattern": "src/**/*.ts"
    }
  }
}

Run Tests on Change

{
  "hooks": {
    "PostEdit": {
      "command": "npm test -- --related",
      "pattern": "src/**/*.ts"
    }
  }
}

Notify on Complete

{
  "hooks": {
    "PostToolUse": {
      "command": "terminal-notifier -message 'Task complete'",
      "tools": ["bash"]
    }
  }
}

Hook Configuration Options

{
  "hooks": {
    "PostEdit": {
      "command": "string",      // Command to run
      "pattern": "glob",        // File pattern match
      "tools": ["array"],       // Tool types to match
      "timeout": 30000,         // Timeout in ms
      "continueOnError": true   // Don't fail on hook error
    }
  }
}

Advanced Patterns

Chain Multiple Hooks

{
  "hooks": {
    "PostEdit": [
      {
        "command": "prettier --write",
        "pattern": "**/*.ts"
      },
      {
        "command": "eslint --fix",
        "pattern": "**/*.ts"
      }
    ]
  }
}

Conditional Hooks

{
  "hooks": {
    "PostEdit": {
      "command": "./scripts/validate.sh",
      "pattern": "src/critical/**/*"
    }
  }
}

Best Practices

Keep Hooks Fast

Slow hooks break flow:

// Good - fast
{ "command": "prettier --write" }
 
// Bad - slow
{ "command": "npm run build && npm test" }

Fail Gracefully

{
  "continueOnError": true,
  "timeout": 5000
}

Log Output

Debug with verbose logging:

{
  "command": "./hook.sh 2>&1 | tee hook.log"
}

Next Steps

In the next module, you'll learn about testing and CI/CD integration for production deployments.

Share