Hooks are shell commands Claude Code runs automatically at lifecycle events such as PreToolUse and PostToolUse. Unlike prompt instructions, which Claude usually follows, hooks run every time, making them ideal for formatting, logging and blocking risky actions.
Prompts are probabilistic, hooks are deterministic
If you write "always run the formatter" in CLAUDE.md, Claude will usually do it. A hook makes it happen every single time, because it's your code running, not the model choosing.
Rule of thumb: if one failure would cost money, break compliance or cause a security issue, enforce it with a hook, not a prompt.
The main hook events
- PreToolUse: before a tool runs. Can block it (e.g. stop edits to
.env). - PostToolUse: after a tool runs. Great for auto-formatting or normalising output.
- UserPromptSubmit: when you send a prompt. Can add context or validate.
- Stop: when Claude finishes responding. E.g. run tests or send a notification.
- SessionStart: when a session begins. Load context or set up the environment.
- Notification: when Claude needs your attention.
Example: auto-format after every edit
Hooks are configured in settings.json (run /hooks to see the ones you have):
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "npx prettier --write \"$CLAUDE_PROJECT_DIR\"" }
]
}
]
}
}
The matcher chooses which tools trigger the hook. The hook receives details about the tool call as JSON on standard input, so scripts can inspect exactly what was edited.
Blocking dangerous actions
A PreToolUse hook script can inspect the incoming tool call and refuse it. Exiting with code 2 blocks the action and feeds your error message back to Claude so it can adjust course.
#!/bin/bash
# block-env.sh: refuse edits to secrets files
input=$(cat)
if echo "$input" | grep -q '\.env'; then
echo "Editing .env files is not allowed" >&2
exit 2
fi
exit 0
Check yourself
Three quick questions to check it stuck.
Ask the tutor
Stuck on something in this lesson? Ask the AI tutor. It answers from this lesson and points you to others that help. Answers are written by AI and can be wrong. Do not include personal details, passwords or company secrets.
Frequently asked
What are hooks in Claude Code?
Hooks are user-defined shell commands that Claude Code runs automatically at events like PreToolUse, PostToolUse, UserPromptSubmit and Stop, giving deterministic control over its behaviour.
How do I block a command in Claude Code with a hook?
Add a PreToolUse hook whose script inspects the tool input and exits with code 2 to block it. The error message on stderr is sent back to Claude.
Should I use a hook or CLAUDE.md for important rules?
Use hooks for rules that must hold every time, such as security or compliance. Use CLAUDE.md for guidance and preferences where occasional deviation is acceptable.