Asking Claude to “always format the code” is a request. A hook is a rule.
Hooks are shell commands that Claude Code runs at fixed points. Add one for PostToolUse with a matcher for the edit tools, in .claude/settings.json. The hook gets the tool input as JSON on stdin, and jq pulls out the file path.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}
Type /hooks to open the hooks browser and check that it shows up. Every file Claude writes or edits is then formatted, whatever the model feels like doing.
A rule in CLAUDE.md is advice that the model can forget on a busy day, while a hook runs every single time. For anything mechanical, formatting being the obvious one, I would pick the hook.
The caveat: you need jq installed. And a Bash command that rewrites a file does not trigger this matcher. For that case the docs point to a FileChanged hook.
Further reading: Automate actions with hooks – Claude Code docs, On this site: add a Notification hook so Claude Code pings you when it waits, On this site: block edits to .env with a PreToolUse hook that exits 2