Volver a PodcastsClaude
Claude Code 101
Hooks en Claude Code
Hooks let you run commands at different points in Claude code's life cycle.
Los hooks te permiten ejecutar comandos en diferentes momentos del ciclo de vida de Claude Code.
The key difference between hooks and everything else we covered is that hooks are deterministic.
La diferencia clave entre los hooks y todo lo demás que hemos visto es que los hooks son deterministas.
They always run.
Siempre se ejecutan.
So, put it this way.
Dicho de otra manera.
You can tell Claude in your claude.md file to run prettier after every file edit and most of the time it will do that, but sometimes it won't.
Puedes decirle a Claude en tu archivo claude.md que ejecute prettier después de cada edición de archivo y la mayoría de las veces lo hará, pero a veces no.
It's not perfect.
No es perfecto.
But a hook makes it happen every single time with no exceptions.
Pero un hook hace que ocurra cada vez sin excepciones.
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.
Los casos de uso comunes incluyen el formateo automático después de ediciones de archivos, el registro de todos los comandos ejecutados para cumplimiento normativo, el bloqueo de operaciones peligrosas como modificar archivos de producción, y el envío de notificaciones cuando Claude termina una tarea.
Hooks are configured in your settings.json file.
Los hooks se configuran en tu archivo settings.json.
You pick an event, optionally set a matcher for which tool it applies to, and provide a command to run.
Eliges un evento, opcionalmente configuras un matcher para la herramienta a la que se aplica, y proporcionas un comando a ejecutar.
User prompts submit runs when you submit a prompt before Claude processes it.
UserPromptSubmit se ejecuta cuando envías un prompt antes de que Claude lo procese.
Pre-tool use which runs before a tool call, post-tool use runs after a tool call completes.
PreToolUse se ejecuta antes de una llamada de herramienta, PostToolUse se ejecuta después de que una llamada de herramienta se completa.
Notification runs when Claude sends a notification, and stop runs when Claude finishes responding.
Notification se ejecuta cuando Claude envía una notificación, y Stop se ejecuta cuando Claude termina de responder.
The most common hook.
El hook más común.
Auto formatting after edits.
Formateo automático después de ediciones.
You set a post-tool use hook with a matcher of edit or multi-edit, right?
Configuras un hook PostToolUse con un matcher de edit o multi-edit, ¿verdad?
So, it fires whenever Claude modifies a file.
Así que se dispara cada vez que Claude modifica un archivo.
The command checks the file extension and runs the appropriate formatter.
El comando verifica la extensión del archivo y ejecuta el formateador apropiado.
This could be prettier for TypeScript, go format for go, rough for Python, whatever your project uses.
Podría ser prettier para TypeScript, go format para Go, ruff para Python, lo que use tu proyecto.
Pre-tool use hooks can block tool calls before they execute.
Los hooks PreToolUse pueden bloquear llamadas de herramientas antes de que se ejecuten.
So, your hook receives the tool name and input as JSON on stdin.
Tu hook recibe el nombre de la herramienta y la entrada como JSON en stdin.
If it exits with code two, the action is blocked and the STD error message gets fed back to Claude's feedback so Claude knows why it was blocked and can adjust.
Si termina con el código 2, la acción se bloquea y el mensaje de error estándar se retroalimenta a Claude para que sepa por qué fue bloqueado y pueda ajustarse.
Exit code zero means proceed.
El código de salida 0 significa continuar.
Exit code two means block.
El código de salida 2 significa bloquear.
This is how you enforce hard rules.
Así es como aplicas reglas estrictas.
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.
Bloquear escrituras en un directorio de configuración de producción, bloquear comandos bash que contengan rm-rf, bloquear commits a main, lo que tu equipo necesite garantizar, no solo sugerir.
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.
Los hooks configurados en .Claude/settings.json son de nivel de proyecto y pueden incluirse en tu repositorio. Esto significa que todo tu equipo obtiene los mismos hooks automáticamente.
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.
Usa la variable de entorno del directorio de proyecto de Claude en tus comandos para referenciar scripts almacenados en tu proyecto para que funcionen independientemente del directorio de trabajo actual de Claude.
[music]
[music]
Hooks gives you deterministic control over Claude code's behavior.
Los hooks te dan control determinista sobre el comportamiento de Claude Code.
[music]
[music]
Use post-tool-use for auto-formatting and logging. Use pre-tool-use to block dangerous operations. Configure them in the /hooks or in settings.
Usa PostToolUse para formateo automático y registro. Usa PreToolUse para bloquear operaciones peligrosas. Configúralos en /hooks o en settings.
json
json
[music]
[music]
and check them into your repository so your team gets them, too.
y súbelos a tu repositorio para que tu equipo también los tenga.
If something needs to happen every time without fail, don't put it in a prompt.
Si algo necesita ocurrir cada vez sin falta, no lo pongas en un prompt.
Put it in a hook.
Ponlo en un hook.
[music]
[music]