Transcription
Hooks are hands down one of the best features in Claude Code, and for some reason, a lot of people don't know about them. Sure, spawning parallel sub-agents is cool, but creating a custom hook for linting notifications and blocking specific commands is so much cooler. Let's go through how to do that.
And before we do, don't forget to hit that subscribe button.
To create your first hook, use the `/hooks` slash command, which shows this scary-looking warning because hooks are commands that run without confirmation. So if you destroy your own code with them, don't cry to Anthropic.
There are five types of hooks: pre-tool use, post-tool use, notification stop, and sub-agent stop. For now, we'll go with pre-tool use, which runs the script before tool execution. We'll add a bash matcher, but you could choose from any one of these. And then for the hook, we'll just write `ls` and save it as `user_settings.json`.
At the moment, this isn't really useful, but if we go to our Claude settings, we can edit the hook here as well. Let's change the `ls` command to this, which will save the bash command to a file. So, whenever it uses the bash tool, we'll be able to see whatever command is used by the tool.
These values here are part of the hook input, which is JSON data that a hook receives. So instead of doing this, we could write a script in any language like Python that takes the hook input and creates a more detailed JSON log that looks like this, which could be used for auditing or just improving the use of the tool.
But this is where things get really interesting because in a script, if we trigger an exit code of two, the error gets shown to the model, meaning it can adjust its process. So we can see Claude is creating a Node project, and by default, it's going to use npm. But I have a `use_bun` hook that will stop it from using npm and tell it to use bun instead. So the hook triggers this error, and instead, it uses bun.
But you can also do cool things like show Claude linting errors or block it from accessing sensitive files. And hooks don't need to have a matcher, like for this notification and stop hook, which plays audio whenever it needs my input.
"Task completed successfully."
Or I could even send notifications to my phone with `notify`. The level of control you get with hooks is insane, and I've only just scratched the surface. I didn't even go through using hooks with MCP tools.
Anyway, check out the link in the description to see some of my examples. Again, don't forget to hit subscribe. And until next time, happy coding.
Hey, it's me again. If you enjoyed this video, go and check out Better Stack. It's an amazing product that I use all the time to help me write better, more robust software. And it's got a free tier, so you've got no excuse not to check it out.