Hooks and subagents in Claude Code
Use hooks for things that must run the same way every time, and subagents to keep heavy reading out of the main context.
People often mix these two features up. Hooks are shell commands that Claude Code runs at a fixed point (before or after a tool call, when a turn ends, and so on), independent of the model. A subagent is a separate Claude session with its own context. The main agent hands it a task and it returns a result.
If you write “remember to run gofmt after editing a file” in CLAUDE.md, the model may forget. A hook runs every time. For example, in .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.go) gofmt -w \"$f\" ;; esac"
}
]
}
]
}
}
Claude Code sends a JSON object to the hook’s stdin, and the file path is in tool_input.file_path. matcher is a regex on the tool name. If the file isn’t a .go file, case skips it and exits 0. You need jq in your PATH.
Exit codes matter: 0 means fine, and 2 means block, with the stderr content fed back to Claude. For PreToolUse, exit 2 blocks the command before it runs. If you only need to forbid a few fixed commands, permissions.deny in the same settings file is simpler.
For a Stop hook, exit 2 makes Claude keep working instead of stopping, for example when tests are still failing. If the tests keep failing, the loop never ends. The hook input has a stop_hook_active field, which is true when Claude is continuing because of the stop hook itself. Check this field and exit 0 to break out of the loop.
A subagent is a Markdown file in .claude/agents/ (per project) or ~/.claude/agents/ (per user), and you can create one quickly with /agents. The frontmatter has name, description, tools (if left empty, it uses all tools) and model. The main agent relies on description to decide whether to delegate, so the description should say clearly when to use it. You can also invoke one by name in your prompt.
Things to keep in mind when using subagents:
- A subagent starts with an empty context and knows nothing about the conversation, so it has to re-read files. This is slower and costs more tokens.
- The main agent receives only the final summary and doesn’t see the raw output, such as stack traces.
- They suit tasks that involve a lot of reading but only need a conclusion, such as finding every call site of an old API in the repo. The grep results don’t fill up the main context.
Small tasks that depend heavily on the current session’s context are better left to the main agent.