DEV Community

Zac
Zac

Posted on

Claude Code hooks: what they're for and when they're worth setting up

Claude Code supports hooks — scripts that run automatically before or after specific events. You can trigger them on session start, session end, file writes, and a few other points.

They're useful for specific things. They're overkill for most things. Here's when to actually reach for them.

What hooks can do

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "echo 'Running shell command'"
        }]
      }
    ],
    "PostToolUse": [...],
    "Stop": [...]
  }
}
Enter fullscreen mode Exit fullscreen mode

Hooks go in .claude/settings.json. Each hook specifies when it fires, a matcher (which tool triggers it), and what to run.

Genuinely useful hook patterns

Auto-run tests after file writes. If Claude edits a test file, run the tests automatically:

{
  "matcher": "Write",
  "hooks": [{
    "type": "command",
    "command": "npm test -- --testPathPattern=${file} 2>&1 | tail -20"
  }]
}
Enter fullscreen mode Exit fullscreen mode

This surfaces failures immediately rather than discovering them when you review.

Lint on save. Run ESLint or your linter after Claude writes TypeScript:

{
  "matcher": "Edit",
  "hooks": [{
    "type": "command",
    "command": "npx eslint ${file} --max-warnings 0 2>&1"
  }]
}
Enter fullscreen mode Exit fullscreen mode

Session state checkpoint. Update a checkpoint file on every tool use:

{
  "matcher": ".*",
  "hooks": [{
    "type": "command",
    "command": "echo $(date -u +%Y-%m-%dT%H:%M:%SZ) > /tmp/last-activity"
  }]
}
Enter fullscreen mode Exit fullscreen mode

Useful for monitoring long-running sessions.

What hooks don't do reliably

Hooks don't fire if the session is killed suddenly — container restart, OOM, force quit. If you're using hooks to save important state, add a backup strategy (checkpoint writes inside the session itself, not just hooks).

Hooks also can't modify what Claude does — they run after the fact. You can observe and react, but you can't intercept.

When not to bother

For most workflows, CLAUDE.md rules handle what you'd otherwise use hooks for. "Run the test suite after every file change" works as a rule. It's easier to maintain than a hook, doesn't require JSON, and survives settings resets.

Use hooks when you need something to happen reliably at the system level — test output fed back into the session, external logging, monitoring. Use CLAUDE.md for behavioral rules.

Getting started

If you haven't used hooks before, start with one: auto-run tests after file writes. It's the highest-value hook for most codebases and straightforward to set up. From there, you'll get a feel for when they're worth adding.

More Claude Code configuration patterns: builtbyzac.com/agent-harness.html.

Top comments (0)