Skip to main content

πŸͺ 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.log is detected β†’ Auto-warn

Hook Types​

PostToolUse Hooks​

Triggered: After a tool is used

HookTrigger ConditionAction
prettierAfter editing JS/TS filesAuto-format
tsc-checkAfter editing .ts/.tsxTypeScript type checking
eslintAfter editing JS/TSESLint checking
console-warnFile contains console.logIssue a warning

PreCommit Hooks​

Triggered: Before a Git commit

HookAction
lint-stagedOnly check staged files
type-checkFull type checking
test-affectedRun affected tests

Stop Hooks​

Triggered: Before a session ends

HookAction
console-auditCheck all modified files for console.log
coverage-checkCheck test coverage
security-scanQuick 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​

  1. Keep hooks lightweight - Avoid time-consuming operations
  2. Be specific with triggers - Avoid unnecessary executions
  3. Friendly error messages - Help users understand issues
  4. 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!