Video: Hooks
1. Video: Hooks
Hooks let you run commands at different points in Claude Code's lifecycle. The key difference between hooks and everything else we covered is that hooks are deterministic. They always run. So put it this way, you can tell Claude in your CLAUDE.md file to run Prettier after file edit, and most of the time it will do that, but sometimes it won't. It's not perfect, but a hook makes it happen every single time with no exceptions. Common use cases could include auto-formatting after file edits, logging all executed commands for compliance, blocking dangerous operations like modifying production files, and sending yourself notifications when Claude finishes a task. Hooks are configured in your settings.json file. You pick an event, optionally set a matcher for which tools it applies to, and provide a command to run. UserPromptSubmit runs when you submit a prompt before Claude processes it. PreToolUse, which runs before a tool call. PostToolUse runs after a tool call completes. Notification runs when Claude sends a notification. And Stop runs when Claude finishes responding. The most common hook, auto-formatting after edits. You set a PostToolUse hook with a matcher of Edit or MultiEdit, right? So it fires whenever Claude modifies a file. The command checks the file extension and runs the appropriate formatter. This could be Prettier for TypeScript. Go format for Go, Ruff for Python, whatever your project uses. PreToolUse hooks can block tool calls before they execute. So your hook receives a tool name and input as JSON on stdin. If it exits with code 2, the action is blocked. And the stderr message gets fed back to Claude as feedback, so Claude knows why it was blocked and can adjust. Exit code 0 means proceed. Exit code 2 means block. This is how you enforce hard rules. Block writes to a production config directory. Block bash commands that contain rm -rf. Block commits to main. Whatever your team needs to be guaranteed, not suggested. Hooks configured in .claude/settings.json are project level and can be checked into your repo. This means that your entire team gets the same hooks automatically. Use the CLAUDE_PROJECT_DIR environment variable in your commands to reference scripts stored in your project so they work regardless of Claude's current working directory. Hooks give you deterministic control over Claude Code's behavior. Use PostToolUse for auto-formatting and logging. Use PreToolUse to block dangerous operations. Configure them in the /hooks or in settings.json and check them into your repository so your team gets them too. If something needs to happen every time without fail, don't put it in a prompt. Put it in a hook.2. Let's practice!
Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.