πͺ Hooks
Hooks are actions that execute automatically when specific events occur, automating repetitive tasks.
What Are Hooks?β
Hooks are like a smart butler:
- π When a file is saved β Auto-format
- π¨ When editing TypeScript β Auto type-check
- π« When
console.logis detected β Auto-warn
Hook Typesβ
PostToolUse Hooksβ
Triggered: After a tool is used
| Hook | Trigger Condition | Action |
|---|---|---|
prettier | After editing JS/TS files | Auto-format |
tsc-check | After editing .ts/.tsx | TypeScript type checking |
eslint | After editing JS/TS | ESLint checking |
console-warn | File contains console.log | Issue a warning |
PreCommit Hooksβ
Triggered: Before a Git commit
| Hook | Action |
|---|---|
lint-staged | Only check staged files |
type-check | Full type checking |
test-affected | Run affected tests |
Stop Hooksβ
Triggered: Before a session ends
| Hook | Action |
|---|---|
console-audit | Check all modified files for console.log |
coverage-check | Check test coverage |
security-scan | Quick security scan |
Configuring Hooksβ
Configure in ~/.claude/settings.json:
{
"hooks": {
"postToolUse": [
{
"name": "prettier",
"trigger": "*.{js,ts,tsx,jsx}",
"command": "npx prettier --write"
},
{
"name": "console-warn",
"trigger": "*.{js,ts}",
"pattern": "console.log",
"action": "warn"
}
],
"stop": [
{
"name": "console-audit",
"command": "grep -r 'console.log' --include='*.ts'"
}
]
}
}
Practical Use Casesβ
Scenario 1: Auto-Formattingβ
{
"name": "auto-format",
"trigger": "edit_file",
"filePattern": "*.{ts,tsx}",
"command": "npx prettier --write ${file}"
}
Scenario 2: TypeScript Type Checkingβ
{
"name": "tsc-check",
"trigger": "edit_file",
"filePattern": "*.{ts,tsx}",
"command": "npx tsc --noEmit"
}
Scenario 3: Forbid console.logβ
{
"name": "no-console",
"trigger": "edit_file",
"filePattern": "*.{ts,tsx}",
"pattern": "console.log",
"severity": "error",
"message": "console.log is not allowed in production code!"
}
Hook Execution Flowβ
Best Practicesβ
- Keep hooks lightweight - Avoid time-consuming operations
- Be specific with triggers - Avoid unnecessary executions
- Friendly error messages - Help users understand issues
- Configurable toggles - Allow temporary disabling
π‘ Tip: Hooks are powerful tools for boosting development efficiency, but too many hooks can slow down your workflow β add them wisely!