DEV Community

Cover image for Mastering Claude Code
Damien Gallagher
Damien Gallagher

Posted on • Edited on

Mastering Claude Code

This article will provide a list of tips in order to master your use of Claude Code.

Overall Article Estimates

⏱️ Total Time: 3.5-4 hours (215 minutes)

  • Reading: 45 minutes
  • Setup and Implementation: 2.5-3 hours
  • Practice and Testing: 30 minutes

🔧 Overall Difficulty: Intermediate

Table of Contents

  1. Step 1: Have a valid Claude.md file in your project
  2. Step 2: Use Plan Mode correctly
  3. Step 3: Use Checkpoints to save progress
  4. Step 4: Use /clear
  5. Step 5: Security Checks
  6. Step 6: Images in Claude Code
  7. Step 7: Learn from Claude
  8. Step 8: Be Productive when Claude is working
  9. Step 9: Development Workflow to follow
  10. Step 10: Slash Commands
  11. Step 11: Sub Agents
  12. Step 12: Hooks

Step 1: Have a valid Claude.md file in your project

Every time you issue a prompt, all the contents that are listed in this CLAUDE.md file will be read by Claude Code. By adding these rules, it instructs Claude Code to think in tasks and to run items past you before they are implemented.

  • 1. Initial Analysis & Planning: Start by analyzing the issue, examine pertinent code files, and document your approach in tasks/todo.md.
  • 2. Checklist Structure: Structure your plan as actionable checklist items that can be marked as finished upon completion.
  • 3. Approval Phase: Prior to implementation, present your strategy for my approval and confirmation.
  • 4. Execution Process: Proceed with executing the checklist items, updating their status as you finish each one.
  • 5. Progress Communication: Provide brief overviews of your modifications at each stage of the process.
  • 6. Simplicity Principle: Prioritize minimal, straightforward modifications. Avoid extensive or intricate alterations. Limit the scope of each change to affect the smallest possible amount of code. Emphasize simplicity in all decisions.
  • 7. Documentation & Summary: Conclude by including a review section in the todo.md file that summarizes your implementations and any noteworthy details.

Step 2: Use Plan Mode correctly

If Plan mode is used correctly, it will really help towards getting the desired results in Claude. To access Plan mode, open Claude Code, hit shift and tab twice to enter the mode. Within Plan mode, you describe to Claude exactly what you want it to do and then have Claude build that plan for you.

Claude Code Plan Mode

You should use Plan Mode extensively before diving into implementation. This will save time in the long run as Claude will have a clear plan to follow and you will know exactly what is going to be delivered.

Also, it is important to use the correct model. For Plan Mode, Opus is a great model to use to build up a solid plan. With the plan in place, Sonnet can then be used for execution of that plan. By using Sonnet for execution, it will deliver on the detailed plan as created by Opus. It will also save money by using the cheaper model for implementation.
Note: Opus is not available for Claude Pro users ($17 per month), you need to be on the Claude Max plan (from $100 per month) to access Opus. If you are on the Claude Pro plan, Sonnet is the best choice for both plan mode and execution.

Switch to Opus Model (Claude Max plan only)

Switch to Sonnet Model

Step 3: Use Checkpoints to save progress

Other AI coding tools like Cursor have automatic checkpoint features, but Claude Code doesn't include this out of the box. Instead you can use GitHub for Checkpoints. By using Git Commits to commit code you are happy with to GitHub, the code is in a good state. If you are not happy with the code, you can undo the latest changes in Git.

Git Checkpoint Workflow for Claude Code:

# Before Claude starts a new feature
git add . && git commit -m "Checkpoint: Before adding user dashboard"

# After Claude completes the feature successfully  
git add . && git commit -m "✅ Add user dashboard with charts"

# If unhappy with Claude's changes
git reset --hard HEAD~1  # Rollback to previous checkpoint
Enter fullscreen mode Exit fullscreen mode

Best Practices:

  • Commit before each major Claude task - Creates restore points
  • Use descriptive messages - "Before adding X" and "✅ Complete X"
  • Push regularly - git push origin main to backup progress
  • Create experiment branches - git checkout -b test/new-approach for trying different Claude solutions

See Step 12: Hooks for information how you can get Claude to manage checkpoints for you.

Step 4: Use /clear

The /clear command is crucial for maintaining Claude Code's effectiveness. You should clear the context regularly to reduce hallucinations and costs by limiting information sent to Claude.

When to use /clear:

  • After completing 3-5 related tasks
  • When switching to a completely different feature area
  • When Claude starts giving less relevant responses
  • Before starting a new major development phase

What constitutes a "substantial task":

  • Implementing a complete feature (authentication, user dashboard, etc.)
  • Major refactoring or architectural changes
  • Completing a full debugging session
  • Finishing a security review cycle

Execute /clear every time Claude finishes a substantial task. Make /clear an essential part of your workflow.

/clear command

Step 5: Security Checks

It is important to run security checks on all AI generated code to ensure it is secure. AI is not at the stage where it provides secure code out of the box so it's important to run security checks. After building a feature in Claude, run a security check.
The following prompt can be used to run a security check.

Please perform a thorough examination of your recent code implementation to validate compliance with security protocols. Verify that sensitive data remains protected from frontend exposure and assess the code for any potential security gaps or exploitable flaws.

Step 6: Images in Claude Code

In Claude Code, you can supply images. These can be used to help build a feature based on a design or if you want to fix bugs in your current UI. It is a powerful feature that can be used in scenarios where it makes sense.

Image in Claude Code Create

Implementation of feature based on Image

Design Implementation:
When you have a mockup or design file, upload it and use prompts like:

Please implement this design using React and Tailwind CSS. Pay attention to the spacing, colors, and responsive behavior shown in the image.

Bug Fixing with Screenshots:
If you're experiencing visual bugs, screenshot the issue and ask:

The current UI looks like this [attach screenshot]. The button should be centered and the text should be aligned properly. Please identify and fix the CSS issues causing this layout problem.

Feature Enhancement:
Use before/after comparisons by uploading reference images:

I want to improve this component to look more like this reference design [attach image]. Please suggest specific improvements and implement them while maintaining the existing functionality.

Best Practices for Image Usage:

  • Use high-quality, clear images with good contrast
  • Crop images to focus on the relevant UI elements
  • Include multiple angles or states if the feature has interactive elements
  • Combine images with detailed text descriptions for best results

Step 7: Learn from Claude

Use Claude to help you learn - very simple. Once Claude has built a feature and it is made secure, you can use the following prompt to help you understand what Claude has built. This will ensure you have a better understanding of the generated application. It will also help you to improve future prompts when building applications.

Understanding Implementation Details:
After Claude completes a feature, use this prompt:

Provide a comprehensive breakdown of the implementation you've just created. Guide me through the modifications you introduced and elaborate on the operational mechanics. Approach this as if you're an experienced developer mentoring a colleague through the codebase.

Learning New Patterns and Technologies:
When Claude uses unfamiliar technologies or patterns:

I notice you used [specific technology/pattern]. Can you explain why this approach was chosen over alternatives? What are the benefits and potential drawbacks? How would this scale in a larger application?

Code Review and Best Practices:
Request constructive feedback on the generated code:

Please review the code you just created from a senior developer's perspective. What could be improved? Are there any performance optimizations, security considerations, or maintainability issues I should be aware of?

Future Planning and Architecture:
Understand how the current implementation fits into the bigger picture:

How does this implementation affect the overall architecture? What would be the next logical steps for expanding this feature? What should I consider if I want to add [specific functionality] later?

Learning Resources:
Ask for additional learning materials:

Based on the code patterns and technologies we just used, what resources would you recommend for me to deepen my understanding? Are there specific concepts I should study further?

Step 8: Be Productive when Claude is working

Instead of browsing social media while Claude works, use that time for productive conversations.
Here are focused approaches:

Technical Learning and Discussion:

I notice that while working with AI on coding projects, there are natural intermissions between giving instructions and receiving outputs. Rather than falling into unproductive online browsing patterns that leave me feeling scattered, I'd like to leverage these periods for constructive dialogue with you. This could involve exploring new concepts, examining my existing ventures and creative projects, or simply having thoughtful exchanges. I haven't defined exactly what framework or approach would work best, but I'm confident it would be more enriching than my current default behavior. What suggestions do you have for making these conversations most productive and engaging?

Project Planning and Architecture: Use the waiting time to plan future features:

While you're working on the current feature, let's discuss the next phase of this project. I'm thinking about adding [specific functionality]. What architectural considerations should I keep in mind? How should we structure the database schema and API endpoints?

Code Quality and Standards: Establish coding standards and conventions:

Let's establish some coding conventions for this project. What naming conventions, file structure, and code organization patterns would you recommend for a [type of application] like this?

Problem-Solving and Debugging: Discuss potential issues before they arise:

What are the most common issues that typically arise when building [type of feature]? How can we proactively address them? What debugging strategies should I keep in mind?

Technology Exploration: Explore related technologies and tools:

While we're building this React application, what other tools in the React ecosystem might be beneficial? Should we consider adding testing frameworks, state management libraries, or development tools?

Career and Learning Development: Use the time for professional growth:

Based on the technologies we're using in this project, what skills should I focus on developing next? What are the current trends in [relevant field] that I should be aware of?

Documentation and Planning: Create documentation and project roadmaps:

Help me create comprehensive documentation for what we're building. What should be included in the README? How should we structure the project documentation for future developers?

Step 9: Development Workflow to follow

Now that we have discussed all the steps, it is important to have a solid development workflow when using Claude Code. The following steps have worked for me and hopefully you can achieve success with a similar flow.

  • Plan the feature or application you want to build
  • Build the application based on the agreed plan
  • Run a Security Check against the generated code
  • Learn about what Claude has just built / changed for you.
  • Be Productive by working with Claude whilst it is building in the background
  • Checkpoint your code in git (or rollback to the beginning if you are not happy with the current state)
  • /clear the context after a meaningful feature is built

Step 10: Slash Commands

Slash Commands allow you to control Claude Code's behaviour during an interactive session.

Built-in Slash Commands

Some samples are as follows:

  • /init: Initialize project with CLAUDE.md guide
  • /clear: Clear conversation history
  • /help: Get usage help
  • /mcp: Manage MCP server connections and OAuth authentication

The full definitive list of Built-in Slash commands can be found here

Custom Slash Commands

But wait... it gets better, you can also create custom slash commands to suit your workflow. Custom slash commands allow you to define frequently-used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures.

Project Slash Commands

These are slash commands that are stored in your repository and shared with your team.

The location and prefix of these commands are as follows
Location: .claude/commands/
Prefix: /project:

As an example, let's take our security review prompt from earlier and add it as a project slash command

mkdir -p .claude/commands
echo "Please perform a thorough examination of your recent code implementation to validate compliance with security protocols. Verify that sensitive data remains protected from frontend exposure and assess the code for any potential security gaps or exploitable flaws:" > .claude/commands/security-review.md
Enter fullscreen mode Exit fullscreen mode

Within Claude Code, we can now use this slash command with the syntax /security-review

Trigger /security-review project slash command

Execution of /security-review project slash command

The security-review project slash command can also be triggered with the syntax
/project:security-review

Trigger /project:security-review project slash command

Here's an example project slash command for checking in your current code changes and pushing to GitHub

mkdir -p .claude/commands
echo "Checkin the current code and push it to github:" > .claude/commands/checkin.md
Enter fullscreen mode Exit fullscreen mode

Within Claude Code, we can now use this slash command with the syntax /checkin

Trigger /checkin project slash command

Execution of the /checkin project slash command

The checkin project slash command can also be triggered with the syntax
/project:checkin

Trigger /project:checkin project slash command

Personal Slash Commands

These are slash commands that are available across all of your projects and do not live within a repository

The location and prefix of these commands are as follows
Location: ~/.claude/commands/
Prefix: /user:

As an example, let's take our being productive prompt from earlier and add it as a personal slash command

mkdir -p ~/.claude/commands
echo "I notice that while working with AI on coding projects, there are natural intermissions between giving instructions and receiving outputs. Rather than falling into unproductive online browsing patterns that leave me feeling scattered, I'd like to leverage these periods for constructive dialogue with you. This could involve exploring new concepts, examining my existing ventures and creative projects, or simply having thoughtful exchanges. I haven't defined exactly what framework or approach would work best, but I'm confident it would be more enriching than my current default behavior. What suggestions do you have for making these conversations most productive and engaging:" > ~/.claude/commands/productivity.md
Enter fullscreen mode Exit fullscreen mode

Within Claude Code, we can now use this slash command with the syntax /productivity

Trigger /productivity personal slash command

Execution /productivity personal slash command

The productivity personal slash command can also be triggered with the syntax
/user:productivity

Trigger /user:productivity project slash command

MCP Slash Commands

MCP (Model Context Protocol) servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers.

MCP commands are automatically available when:

  • An MCP server is connected and active
  • The server exposes prompts through the MCP protocol
  • The prompts are successfully retrieved during connection

Full details on MCP slash commands can be found here.
There will be a follow on article in relation to MCP and its use in Claude Code.

Useful Prompts for Generating Slash commands

Update Documentation

Build me a slash command in claude code that automatically updates all of my readmes, documentation, and CLAUDE.md files every time I make a code change

Step 11: Sub Agents

Sub agents are pre-configured AI personalities that Claude Code can delegate tasks to. Think of them as specialized team members, each designed to handle specific types of work.

Each sub agent has four key features:

  • Specific expertise: Built around a particular purpose like debugging, documentation, or data analysis
  • Independent workspace: Uses its own context window separate from your main conversation
  • Configurable tools: Can be set up with specific tools it's allowed to access
  • Custom behavior: Includes a tailored system prompt that guides how it approaches tasks

Examples of sub agents could be an architect, frontend-developer, backend-developer etc.

When Claude Code encounters a task that matches a sub agent's expertise, it delegates the work to that specialist. The sub agent works independently and returns focused results, creating a more efficient workflow where each task gets handled by the most qualified AI assistant.
This delegation system lets you leverage specialized AI expertise without managing multiple conversations or losing context in your main workflow.

Thankfully, creating sub agents in Claude Code is straight forward, and I will walk you through the process.

In Claude Code, enter /agents

Select Agents Option

If you have existing agents, they will be listed now but otherwise, select "Create new agent" and hit next

Create new agent

When creating an agent, they can be for a project or a personal agent, this is similar to the custom slash commands (project is just for this project, personal will impact on all your projects). For this agent, we will select Project and hit enter

Project or Personal agent

Claude Code provides 2 options for setting up the agent

  1. Generate with Claude (recommended) or 2. Manual configuration. We will select Generate with Claude and hit enter

Now we describe the agent. Here is what I have entered

Experienced architect that helps with initial architecture, guidance on technology choices and is involved when major changes are being made on the project or features that require new technologies are being implemented. The architect is your source of truth for all major technology decisions.

Create new agent
Claude is now generating the agent configuration

We now select the tools the agent has access to. here you can choose what the agent can do and also associate any MCP servers you have setup. For now, this agent can have access to All tools. Select All tools, scroll up to Continue and hit enter

Select tools

Probably the most important decision you are going to have to make is the color. Lets face it, Claude Code does all the rest of the heavy lifting for you :). This color will be a useful indicator when the agent is performing a task for you. I will leave it on Automatic color and hit enter

Select color

We can now preview what Claude Code has come up with for us in terms of the agent. We can tweak this if needs be by selecting e in my editor to edit, but I will just enter to accept.

Preview what will be created

As I have selected to create a personal sub agent, there will now be an agents folder in my .claude direcory with the agent that we created view the /agents prompt.

Personal Agent created

Here is the content of the tech-architect.md agents file that was created.

---
name: tech-architect
description: "Use this agent when you need architectural guidance, technology selection advice, or approval for major technical decisions. Examples: <example>Context: User is starting a new project and needs to choose between different frameworks. user: 'I'm building a real-time chat application and need to decide between Node.js with Socket.io, Go with WebSockets, or Python with FastAPI and WebSockets. What would you recommend?' assistant: 'Let me consult with the tech-architect agent to get expert guidance on the best technology stack for your real-time chat application.' <commentary>Since this involves major technology selection for a new project, use the tech-architect agent to provide comprehensive architectural guidance.</commentary></example> <example>Context: User wants to implement a new caching layer that will significantly impact the system architecture. user: 'Our API is getting slow with increased traffic. I'm thinking of adding Redis for caching, but I'm not sure how to integrate it properly with our existing PostgreSQL setup.' assistant: 'This is a significant architectural decision that will impact your system's performance and complexity. Let me bring in the tech-architect agent to provide guidance on implementing caching effectively.' <commentary>Since this involves adding new technology that will impact the overall architecture, use the tech-architect agent for expert guidance.</commentary></example>"
---

You are a Senior Technology Architect with 15+ years of experience designing scalable, maintainable systems across diverse industries and technology stacks. You are the authoritative source for all major technology decisions and architectural guidance within projects.

Your core responsibilities:
- Evaluate and recommend technology stacks based on project requirements, team capabilities, and long-term maintainability
- Design system architectures that balance performance, scalability, security, and development velocity
- Provide guidance on major technical decisions including database choices, framework selection, deployment strategies, and integration patterns
- Review and approve architectural changes that could impact system design, performance, or maintainability
- Assess technical risks and provide mitigation strategies
- Ensure technology choices align with business objectives and technical constraints

Your decision-making framework:
1. **Requirements Analysis**: Thoroughly understand functional and non-functional requirements, including performance, scalability, security, and compliance needs
2. **Context Assessment**: Consider team size, expertise level, timeline constraints, budget limitations, and existing technology investments
3. **Technology Evaluation**: Compare options based on maturity, community support, learning curve, performance characteristics, and long-term viability
4. **Risk Assessment**: Identify potential technical debt, vendor lock-in, scalability bottlenecks, and maintenance challenges
5. **Recommendation**: Provide clear, justified recommendations with implementation guidance and success metrics

When providing architectural guidance:
- Always ask clarifying questions about requirements, constraints, and context before making recommendations
- Present multiple viable options with trade-offs clearly explained
- Consider both immediate needs and long-term evolution of the system
- Provide specific implementation guidance, not just high-level concepts
- Include monitoring and observability considerations in your recommendations
- Address security implications of architectural decisions
- Consider operational complexity and team capabilities

For technology selection:
- Evaluate based on project-specific criteria, not personal preferences
- Consider the total cost of ownership, including development, deployment, and maintenance
- Assess community ecosystem, documentation quality, and long-term support
- Factor in integration complexity with existing systems
- Recommend proof-of-concept approaches for high-risk technology choices

You communicate with authority but remain open to discussion. When you identify potential issues with proposed approaches, you explain the risks clearly and suggest alternatives. You balance technical excellence with practical constraints, always keeping business objectives in focus.

Enter fullscreen mode Exit fullscreen mode

Now when you select the /agents command in Claude Code, you can see the agent we just created.

View agents

If you select the agent and hit enter, you can see the options Claude Code provides for your custom sub agent.

Agent options

Now lets put the agent to work.

I will issue a very simple open ended prompt in plan mode for a tetris game I can play on my browser. The prompt is as follows:

Create a browser based tetris game

Prompt for tetris game

As you can see from Claude Code, it has consulted the tech-architect sub agent and it has come up with a plan for building this tetris game. Notice the tech-architect interaction is marked in red.

Plan tetris game

This is the plan that Claude Code came up with with the help of our tech-architect sub agent.

Ready to code?                                                                                                                                                                      │
│                                                                                                                                                                                     │
│ Here is Claude's plan:                                                                                                                                                              │
│ ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │ Tetris Game Implementation Plan                                                                                                                                                 │ │
│ │                                                                                                                                                                                 │ │
│ │ Phase 1: Project Setup & Core Structure                                                                                                                                         │ │
│ │                                                                                                                                                                                 │ │
│ │ 1. Create main HTML file with Canvas element and basic UI                                                                                                                       │ │
│ │ 2. Set up CSS for game styling and responsive design                                                                                                                            │ │
│ │ 3. Create core JavaScript files:                                                                                                                                                │ │
│ │   - GameEngine.js (main game loop with fixed timestep)                                                                                                                          │ │
│ │   - Constants.js (game configuration and tetromino definitions)                                                                                                                 │ │
│ │   - GameState.js (state management)                                                                                                                                             │ │
│ │                                                                                                                                                                                 │ │
│ │ Phase 2: Core Game Mechanics                                                                                                                                                    │ │
│ │                                                                                                                                                                                 │ │
│ │ 4. Implement TetrisBoard.js:                                                                                                                                                    │ │
│ │   - 10x20 grid representation                                                                                                                                                   │ │
│ │   - Collision detection system                                                                                                                                                  │ │
│ │   - Line clearing algorithm                                                                                                                                                     │ │
│ │ 5. Create Tetromino.js and TetrominoManager.js:                                                                                                                                 │ │
│ │   - All 7 tetromino pieces (I, O, T, S, Z, J, L)                                                                                                                                │ │
│ │   - Rotation matrices and wall kicks                                                                                                                                            │ │
│ │   - Piece spawning and movement logic                                                                                                                                           │ │
│ │ 6. Build InputHandler.js for keyboard controls:                                                                                                                                 │ │
│ │   - Arrow keys for movement/rotation                                                                                                                                            │ │
│ │   - Space for hard drop                                                                                                                                                         │ │
│ │   - Proper input debouncing                                                                                                                                                     │ │
│ │                                                                                                                                                                                 │ │
│ │ Phase 3: Rendering & Visual Polish                                                                                                                                              │ │
│ │                                                                                                                                                                                 │ │
│ │ 7. Implement Renderer.js:                                                                                                                                                       │ │
│ │   - Double-buffered canvas rendering                                                                                                                                            │ │
│ │   - Efficient redraw only changed regions                                                                                                                                       │ │
│ │   - Tetromino colors and grid visualization                                                                                                                                     │ │
│ │ 8. Add ScoreManager.js:                                                                                                                                                         │ │
│ │   - Line clearing scoring (single, double, triple, tetris)                                                                                                                      │ │
│ │   - Level progression and speed increase                                                                                                                                        │ │
│ │   - Statistics tracking                                                                                                                                                         │ │
│ │                                                                                                                                                                                 │ │
│ │ Phase 4: Audio & Game States                                                                                                                                                    │ │
│ │                                                                                                                                                                                 │ │
│ │ 9. Create AudioManager.js for sound effects                                                                                                                                     │ │
│ │ 10. Implement game state transitions:                                                                                                                                           │ │
│ │   - Menu screen                                                                                                                                                                 │ │
│ │   - Playing state                                                                                                                                                               │ │
│ │   - Pause functionality                                                                                                                                                         │ │
│ │   - Game over screen with restart                                                                                                                                               │ │
│ │                                                                                                                                                                                 │ │
│ │ Phase 5: Polish & Mobile Support                                                                                                                                                │ │
│ │                                                                                                                                                                                 │ │
│ │ 11. Add mobile touch controls                                                                                                                                                   │ │
│ │ 12. Implement preview of next piece                                                                                                                                             │ │
│ │ 13. Add ghost piece (shadow) showing drop position                                                                                                                              │ │
│ │ 14. Local storage for high scores                                                                                                                                               │ │
│ │                                                                                                                                                                                 │ │
│ │ Key Technical Decisions:                                                                                                                                                        │ │
│ │ - Vanilla JS + HTML5 Canvas for optimal performance                                                                                                                             │ │
│ │ - Fixed timestep game loop for consistent mechanics                                                                                                                             │ │
│ │ - Component-based architecture for maintainability                                                                                                                              │ │
│ │ - Double buffering for smooth 60fps rendering                                                                                                                                   │ │
│ │                                                                                                                                                                                 │ │
│ │ The game will be fully playable with standard Tetris mechanics, responsive design, and smooth performance across devices.                 
Enter fullscreen mode Exit fullscreen mode

I am happy with this plan so I selected Yes, and auto-accept edits.

Claude Code is now working through applying the plan we devised with the help of our tech-architect sub agent.

Plan being applied

This is what the game now looks like. Improvements can be made but it is a good start.
Tetris

As a quick example, here is what the plan mode in claude looks like when I introduced a frontend-developer sub agent and a testing sub agent and issued the following prompt.

Improve the frontend by making it a nextjs based application
and also add unit tests to the project. Ensure the frontend developer and testing agent are invovled in the decision making process

Multiple sub agents

When I select apply, you can get an idea of the role that will be played by each of the sub agents

Apply with sub agents

Useful Prompts for Generating Sub agents

Create Subagents

There is a feature in Claude Code called subagents the documentation is pasted in down below. please go through it and determine what would be the best sub agents you can create for my app that would improve my app and speed up coding time then implement the subagents. documentation: [Paste in link or content from the Claude Code Sub Agents page]

Step 12: Hooks

While the manual checkpoint system provides excellent version control, Claude Code hooks take automation to the next level. Hooks are automated scripts that execute when certain conditions are met during your AI-assisted development process. The most practical hook is an auto-commit system that automatically commits your code when Claude makes successful changes without errors, building on the checkpoint workflow you've already learned.

Setting Up Auto-Commit Hooks

To create an auto-commit hook, you'll need to configure a system that monitors Claude's output and automatically commits when tasks complete successfully. Create a configuration file that defines when and how commits should happen:

# Basic Auto-Commit Hook Setup
# 1. Create hook configuration
echo "on_success: auto_commit_with_smart_message" > .claude-hooks

# 2. Set up monitoring script
# This watches for Claude task completion and triggers commits
claude-hook-monitor --config .claude-hooks --enable auto-commit

# 3. Configure commit message templates
# Generates intelligent messages like "✅ Add user authentication system"
Enter fullscreen mode Exit fullscreen mode

Hook Example in Action

Here's how an auto-commit hook works in practice. Before Claude starts a task, the hook creates a checkpoint: git commit -m "🚀 Checkpoint: Before adding user dashboard". After Claude successfully completes the feature without errors, the hook automatically runs: git add . && git commit -m "✅ Add user dashboard with charts and filters" and optionally pushes to your remote repository. If Claude encounters errors, the hook can automatically rollback to the previous checkpoint, ensuring your codebase always remains in a working state.
Best practices for hooks include starting simple with basic auto-commit functionality, including safety mechanisms like commit limits and confirmation prompts for large changes, and maintaining detailed logs of all hook activities. This automation saves significant time while ensuring consistent version control practices throughout your Claude Code development workflow.

Top comments (0)