Skip to content

Professional tips and tricks for effectively using Claude Code for agentic coding

Notifications You must be signed in to change notification settings

jstep/claude-code-tips

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Claude Code Tips and Tricks

This guide covers professional tips for effectively using Claude Code for agentic coding. Claude Code is Anthropic's open-source AI assistant that brings the power of Claude directly into your terminal. It functions as a conversational, "agentic" command-line tool that can reason about your requests, choose tools, and execute multi-step plans to help with your development workflow.

Table of Contents

  1. Getting Started
  2. Tip 1: Use CLAUDE.md for Persistent Context
  3. Tip 2: Create Custom Slash Commands
  4. Tip 3: Extend Claude Code with MCP Servers
  5. Tip 4: Leverage Context Management
  6. Tip 5: Use Checkpoints and Rewind
  7. Tip 6: Read Google Docs, Sheets with MCP
  8. Tip 7: Reference Files with @ Symbol
  9. Tip 8: Use Skills for Recurring Workflows
  10. Tip 9: System Troubleshooting & Configuration
  11. Tip 10: Auto Mode - Skip Permissions
  12. Tip 11: Headless & Scripting Mode
  13. Tip 12: Save and Resume Sessions
  14. Tip 13: Multi-Directory Workspace
  15. Tip 14: Organize Files with AI
  16. Tip 15: Compress Conversations with /compact
  17. Tip 16: Shell Commands with ! Syntax
  18. Tip 17: Leverage All CLI Tools
  19. Tip 18: Multimodal AI - Images and More
  20. Tip 19: Use Hooks for Automation
  21. Tip 20: Prompt Caching - Reduce Costs and Latency
  22. Tip 21: /copy Command ❌ NOT AVAILABLE
  23. Tip 22: Master Keyboard Shortcuts
  24. Tip 23: Customize with Settings
  25. Tip 24: VS Code Integration
  26. Tip 25: GitHub Integration
  27. Tip 26: Use Subagents for Complex Tasks
  28. Tip 27: Plan Mode for Complex Problems
  29. Tip 28: Plugins for Extended Functionality

Getting Started

Installation

You can install Claude Code via multiple methods:

MacOS/Linux:

curl -fsSL https://claude.ai/install.sh | bash

Homebrew (MacOS):

brew install --cask claude-code

Windows:

irm https://claude.ai/install.ps1 | iex

NPM:

npm install -g @anthropic-ai/claude-code

Authentication

On first use, you'll be prompted to log in with your Anthropic account. Claude Code is available to Max, Pro, Team, and Enterprise users.

Basic Usage

To start an interactive session, navigate to your project directory and run:

cd your-project
claude

For non-interactive (headless) usage, use the -p flag:

claude -p "Create a React component for user login"

Tip 1: Use CLAUDE.md for Persistent Context

Quick use-case: Stop repeating yourself. Provide project-specific context by creating a CLAUDE.md file in your project root. This ensures Claude always has important background knowledge.

How It Works

Create a .claude folder (if not present) in your project root and add a CLAUDE.md file:

# Project Phoenix - AI Assistant Context

## Code Standards

- All TypeScript code must follow strict typing
- Use functional components with React hooks
- Prefer composition over inheritance

## Project Architecture

- Frontend: React + TypeScript + Tailwind
- Backend: Node.js + Express + PostgreSQL
- API follows REST conventions

## Key Commands

- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint`

Claude Code will automatically load this context every time you start a session in this project. This means Claude is always primed with your project's conventions, avoiding repetitive explanations.

Pro Tips

  • Place CLAUDE.md at your project root for project-wide context
  • You can also use global context at ~/.claude/CLAUDE.md for cross-project preferences
  • Keep it organized and concise - focus on what Claude needs to know most
  • Use Claude to help generate your initial CLAUDE.md by asking: "Generate a CLAUDE.md for this project"

Tip 2: Create Custom Slash Commands

Quick use-case: Automate repetitive tasks with custom shortcuts. Create /test-gen to generate unit tests, or /commit to create conventional commit messages.

Creating Custom Commands

Custom slash commands are markdown files stored in:

  • Project commands: .claude/commands/ (shared with your team)
  • Personal commands: ~/.claude/commands/ (available across all projects)

Example: Create a code review command

Create .claude/commands/review.md:

---
description: Comprehensive code review
allowed-tools: Read, Grep, Glob, Bash(git diff:*)
model: sonnet
---

# Code Review

## Changed Files

!`git diff --name-only HEAD~1`

## Detailed Changes

!`git diff HEAD~1`

## Review Checklist

Review the changes for:

1. Code quality and readability
2. Security vulnerabilities
3. Performance implications
4. Test coverage
5. Documentation updates

Provide specific, actionable feedback organized by priority.

Now you can run /review anytime to execute this workflow.

Command Features

  • Arguments: Use $ARGUMENTS to pass parameters
  • Shell execution: Use !git command`` to run commands and inject output
  • Model selection: Specify model: haiku or model: sonnet in frontmatter
  • Tool restrictions: Use allowed-tools to limit what Claude can do

Example with arguments:

.claude/commands/test.md:

---
description: Run tests with optional pattern
allowed-tools: Bash, Read, Edit
argument-hint: [test-pattern]
model: haiku
---

Run tests matching pattern: $ARGUMENTS

1. Detect the test framework
2. Run tests with the provided pattern
3. If tests fail, analyze and fix them
4. Re-run to verify fixes

Usage: /test user-auth

Pro Tips

  • Share commands by committing them to .claude/commands/ in your repo
  • Use model: haiku for fast, simple tasks (linting, commits)
  • Use model: sonnet for complex reasoning (debugging, architecture)
  • Ask Claude to create commands for you: "Create a /lint command that fixes ESLint issues"

Tip 3: Extend Claude Code with MCP Servers

Quick use-case: Connect Claude to external systems like Google Drive, Figma, Slack, or custom databases through Model Context Protocol (MCP) servers.

What is MCP?

MCP (Model Context Protocol) is a standard that allows Claude to interface with external tools and services. You can use pre-built MCP servers or create your own.

Adding MCP Servers

Via CLI:

claude mcp add myserver

Via configuration file:

Create or edit .mcp.json in your project root:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"]
    },
    "google-drive": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-gdrive"]
    }
  }
}

Available MCP Integrations

Popular MCP servers include:

  • Google Drive: Access docs, sheets, and files
  • GitHub: Manage issues, PRs, and code
  • Slack: Send messages and read channels
  • Figma: Fetch designs and components
  • Puppeteer: Browser automation
  • Database connectors: PostgreSQL, MySQL, etc.

Using MCP Tools

Once configured, MCP tools are available as slash commands with the prefix mcp__:

# List GitHub PRs
/mcp__github__list_prs

# Review a specific PR
/mcp__github__pr_review 456

# Read a Google Doc
/mcp__google-drive__read_doc <doc-id>

Pro Tips

  • Use --mcp-debug flag when launching to troubleshoot MCP issues: claude --mcp-debug
  • Check .mcp.json into git to share MCP configuration with your team
  • List available MCP tools with /mcp command
  • OAuth-based MCP servers can securely connect to APIs without exposing credentials

Tip 4: Leverage Context Management

Quick use-case: Keep important facts and decisions at Claude's fingertips by managing context effectively through CLAUDE.md and project documentation.

Effective Context Strategies

  1. Use CLAUDE.md for persistent knowledge (see Tip 1)
  2. Reference files explicitly with @ (see Tip 7)
  3. Document decisions and patterns
  4. Keep context organized and relevant

Context Best Practices

Document key decisions:

## Architectural Decisions

### Date: 2025-01-15

Decision: Use PostgreSQL over MongoDB
Rationale: Need ACID compliance for financial data

Define patterns:

## Common Patterns

### Error Handling

All async functions should use try-catch with proper error logging:

```typescript
try {
  const result = await apiCall();
  return result;
} catch (error) {
  logger.error("API call failed", { error });
  throw new ApplicationError("Operation failed");
}
```

Managing Context Size

  • Keep CLAUDE.md focused on essential information
  • Use subdirectories for detailed documentation
  • Reference specific docs when needed: "Check @docs/api-design.md for API patterns"
  • Regularly update context as the project evolves

Tip 5: Use Checkpoints and Rewind

Quick use-case: Claude Code automatically tracks file edits as checkpoints. Use the rewind feature to undo changes and restore previous code states during your session.

How Checkpointing Works

Claude Code automatically creates a checkpoint for every user prompt. This allows you to:

  • Rewind to any previous point in your session
  • Recover code states even after accepting changes
  • Choose what to rewind: conversation, code, or both
  • Maintain session history across restarts (cleaned up after 30 days)

Using the Rewind Feature

Two ways to access rewind:

  1. Press Esc twice (Esc + Esc)
  2. Use the /rewind command

Both open the interactive rewind menu with three options:

Rewind Options

1. Conversation only

  • Rewind to a previous user message
  • Keep all code changes
  • Useful when you want to try a different approach without losing work

2. Code only

  • Revert file changes to a previous checkpoint
  • Keep the conversation history
  • Perfect for undoing code changes that introduced bugs

3. Both code and conversation

  • Restore both conversation and files to a prior point
  • Complete rollback to any checkpoint in the session
  • Most comprehensive recovery option

What Gets Tracked

Tracked:

  • All file edits made during the session
  • Checkpoint created for every user prompt
  • Changes persist across session restarts

Not tracked:

  • Bash command changes (file system modifications)
  • External file modifications (outside Claude Code)
  • Changes from other concurrent sessions

Best Practices

  • Experiment freely: Checkpoints let you try different approaches safely
  • Quick recovery: Rewind is faster than git for session-level undo
  • Combine with git: Checkpoints complement but don't replace version control
  • 30-day retention: Checkpoints auto-clean after 30 days (configurable)

Pro Tips

  • Double-tap Esc for quick access to rewind
  • Use "Code only" rewind to fix bugs while keeping context
  • Use "Conversation only" to retry prompts with different wording
  • Checkpoints are perfect for exploring multiple solutions
  • For long-term history, still commit to git regularly

Note: Checkpointing is designed for quick, session-level recovery. For production code and long-term version control, always use git commits.


Tip 6: Read Google Docs, Sheets with MCP

Quick use-case: Access Google Workspace documents directly from Claude Code by pasting links or doc IDs.

Setup

Configure Google Drive MCP in .mcp.json:

{
  "mcpServers": {
    "google-drive": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-gdrive"]
    }
  }
}

Usage

Once configured, you can:

# Reference a Google Doc
"Summarize the requirements from https://docs.google.com/document/d/..."

# Read a spreadsheet
"Extract budget data from https://docs.google.com/spreadsheets/d/..."

Claude will use the MCP server to fetch and read the content, subject to your Google Drive permissions.

Pro Tips

  • OAuth authentication is handled by the MCP server
  • Ensure proper permissions are set on documents
  • Works with Docs, Sheets, Slides, and Drive files
  • Can also write back to docs if the MCP server supports it

Tip 7: Reference Files with @ Symbol

Quick use-case: Point Claude directly to files and directories for precise context. Instead of describing code, show it: @./src/main.ts

File Reference Syntax

Single file:

"Explain this code: @./src/auth.ts"

Multiple files:

"Compare @./client/api.ts and @./server/routes.ts"

Entire directory:

"Refactor all files in @./utils/ to use async/await"

Images:

"Describe what you see in @./design/mockup.png"

How It Works

The @ syntax includes file contents directly in the prompt context. Claude can read:

  • Source code (all languages)
  • Text files (.txt, .md, etc.)
  • Configuration files
  • Images (PNG, JPEG, etc.)
  • PDFs (text extraction)

Best Practices

  • Be explicit: Always use @ for files you want Claude to see
  • Scope appropriately: Reference specific files over entire directories when possible
  • Image analysis: Claude can read screenshots, diagrams, mockups, and perform OCR
  • Ignore files: Claude respects .gitignore and .claudeignore patterns

Pro Tips

  • Use @ for precise debugging: "Fix the bug in @./src/payment.ts at line 145"
  • Chain file references: "Apply the pattern from @./patterns/auth.ts to @./src/user.ts"
  • Avoid referencing huge directories unnecessarily - be targeted

Tip 8: Use Skills for Recurring Workflows

Quick use-case: Skills are like supercharged slash commands that Claude can invoke automatically based on context. Perfect for workflows that should run automatically.

What are Skills?

Skills are sets of instructions and/or code that Claude can run on-demand or automatically. Unlike slash commands (which you invoke manually), Skills can be triggered by Claude when it detects the right context.

Creating a Skill

Skills are stored in .claude/skills/ as markdown files:

Example: .claude/skills/slack-notifier.md

---
description: Notify team on Slack when pushing features
trigger: after_git_push
allowed-tools: Bash, MCP(slack)
---

# Slack Notification Skill

When code is pushed to the main branch:

1. Get the commit message and changes
2. Format a concise summary
3. Post to #engineering channel on Slack
4. Include link to commit

Use professional but friendly tone.

Skill vs Slash Command

Feature Slash Command Skill
Invocation Manual (/command) Automatic or manual
Trigger User types command Context-based
Scope Single task Workflow automation
Best for On-demand actions Recurring patterns

Pro Tips

  • Use Skills for "always do this" workflows
  • Use Slash Commands for "I want to do this now" actions
  • Skills can call other tools and MCP servers
  • Document your Skills in CLAUDE.md so Claude knows when to use them

Tip 9: System Troubleshooting & Configuration

Quick use-case: Use Claude Code for general system administration tasks, not just coding. Fix dotfiles, diagnose errors, customize your dev environment.

System Tasks Claude Can Help With

Edit configuration files:

"Fix my .bashrc file - it has a PATH error"
"Optimize my .zshrc for development"
"Configure my .gitconfig with proper aliases"

Diagnose system issues:

"I'm getting EACCES errors with npm install - help me fix this"
"Why is my Docker daemon not starting?"
"Debug this Python import error: [paste error]"

Setup and installation:

"Install and configure PostgreSQL on macOS"
"Set up Docker with proper user permissions"
"Configure my SSH keys for GitHub"

Pro Tips

  • Run Claude from your home directory for system-wide tasks
  • Claude can read system logs and config files
  • Always review system commands before approving them
  • Use for workstation customization and environment setup

Tip 10: Auto Mode - Skip Permissions (Use with Caution)

Quick use-case: Let Claude work without asking permission for every action. Similar to "YOLO mode" - fast but requires trust.

Enabling Auto Mode

Method 1: Command flag

claude --dangerously-skip-permissions

Method 2: Interactive toggle Press Esc during a session to enter Auto Mode

Method 3: Specific permissions Use /permissions command to configure which tools can run without approval:

/permissions
# Then approve specific command patterns

What Auto Mode Does

  • Claude executes file edits immediately
  • Runs bash commands without confirmation
  • Makes git commits and pushes
  • Installs packages automatically

When to Use Auto Mode

Good use cases:

  • Working on features with frequent small edits
  • Running established workflows
  • In a sandboxed environment
  • When using hooks for validation

Avoid auto mode when:

  • Running destructive operations
  • In production environments
  • Working with sensitive data
  • First time on a new codebase

Safety Measures

  1. Use git: Commit frequently so you can revert
  2. Configure hooks: Add validation hooks that run before accepting changes
  3. Selective approval: Use /permissions to allow only safe commands
  4. Stay alert: You can press Esc to interrupt at any time

Pro Tip

Combine auto mode with validation hooks:

{
  "hooks": {
    "before_edit_applied": ["prettier --write {file}"],
    "after_edit_applied": ["npm run typecheck {file}"]
  }
}

This ensures code quality even in auto mode.


Tip 11: Headless & Scripting Mode

Quick use-case: Integrate Claude Code into CI/CD pipelines, scripts, and automation by running it non-interactively.

Basic Headless Usage

Use the -p flag for single-shot execution:

claude -p "Run tests and fix any failures"

Output Formats

Stream JSON for programmatic use:

claude -p "Analyze this code" --output-format stream-json

Capture output:

result=$(claude -p "Generate API documentation")
echo "$result" > docs/api.md

CI/CD Integration

GitHub Actions example:

name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code
      - name: Review PR
        run: |
          claude -p "Review the changes in this PR and comment on quality" \
                 --output-format stream-json

Pre-commit hook example:

#!/bin/bash
# .git/hooks/pre-commit

claude -p "Run linter and tests, fix any issues" \
       --dangerously-skip-permissions

Automation Examples

Nightly log analysis:

# crontab entry
0 2 * * * cd /app && claude -p "Analyze yesterday's error logs and create a report"

Automated refactoring:

claude -p "Update all API calls to use new error handling pattern" \
       --output-format stream-json > refactor-log.json

Pro Tips

  • Headless mode doesn't persist between sessions
  • Use environment variables for sensitive data
  • Parse JSON output for integration with other tools
  • Combine with --dangerously-skip-permissions for full automation

Tip 12: Save and Resume Sessions

Quick use-case: Claude Code automatically saves your conversation history locally. Resume your most recent session or choose from previous conversations to continue where you left off.

How Sessions Work

Claude Code automatically saves all session history locally. This allows you to:

  • Pause work and come back later
  • Switch between different projects/tasks
  • Preserve full conversation context and tool usage
  • Maintain model settings across sessions

What gets saved:

  • Full conversation history
  • Tool usage and results
  • Model and configuration settings
  • Working directory context

Resuming Sessions

Continue most recent session:

# Resume your latest conversation automatically
claude --continue

# Or use the short form
claude -c

This immediately continues your most recent session, loading the full conversation context.

Choose from previous sessions:

# Interactive session selector
claude --resume

# Navigate with arrow keys
# Press Esc to exit selector

The --resume flag opens an interactive menu showing your recent sessions. Use arrow keys to browse and select which conversation to resume.

Using with Non-Interactive Mode

Sessions work seamlessly with headless mode:

# Continue previous session non-interactively
claude --continue --print "Show me what we accomplished so far"

# Short form
claude -c -p "Continue implementing the feature"

Perfect for CI/CD pipelines or scripts that need context from previous runs.

Session Management

Viewing session info:

Sessions are stored locally and include:

  • Complete conversation transcript
  • All file changes and edits
  • Tool execution history
  • Checkpoint state (for rewind feature)

Session persistence:

  • Sessions persist across computer restarts
  • Each directory can have independent session history
  • CLAUDE.md context is always loaded automatically

Best Practices

1. Resume for continuity:

# Start your day
claude --continue
"What were we working on yesterday?"

2. Document important decisions:

# Add key findings to CLAUDE.md for permanent reference
"Add this architectural decision to CLAUDE.md:
We're using Redis for caching with 1-hour TTL"

3. Use with git commits:

# Commits serve as natural session boundaries
claude --continue
"Review changes since last commit and create a summary"

4. Selective session resume:

# Use --resume to pick specific sessions
claude --resume
# Select "Feature: User Authentication" from 2 days ago

Pro Tips

  • Use --continue for quick resumption of your latest work
  • Use --resume when you need to go back to a specific conversation
  • Sessions work per-directory, so different projects have independent history
  • Combine with /compact to clean up long sessions while preserving key context
  • Use /rewind to undo changes within a session

Permanent Context

For information that should persist across all sessions:

# Update CLAUDE.md with permanent project knowledge
"Add to CLAUDE.md:
## Database Schema
- Users table: id, email, password_hash, created_at
- Posts table: id, user_id, title, content, published_at"

CLAUDE.md provides permanent context that's loaded in every session, complementing session-specific history.


Tip 13: Multi-Directory Workspace

Quick use-case: Work across multiple repositories or directories simultaneously. Perfect for microservices or monorepo-like structures.

Adding Directories

During launch:

# From any directory
claude

# Then add other directories
/add-dir ../backend
/add-dir ../frontend
/add-dir ~/common-utils

Check workspace:

/workspace
# Shows all directories in current workspace

Usage Examples

Cross-repo changes:

"Update the API client in @../frontend/src/api.ts to match
the new endpoints in @../backend/routes/api.ts"

Shared library updates:

"Apply this pattern from @~/common-utils/auth.ts across
all services in the workspace"

Pro Tips

  • Add directories as needed during development
  • Claude maintains awareness of all added directories
  • Useful for microservices architectures
  • Works well with monorepos

Tip 14: Organize Files with AI

Quick use-case: Let Claude act as your intelligent file organizer. Sort downloads, rename screenshots descriptively, categorize project assets.

File Organization Tasks

Clean up downloads:

"Organize my Downloads folder:
- Move images to Images/
- Move PDFs to Documents/
- Delete temp files
- Archive old installers"

Rename files by content:

"Look at each PNG in @./screenshots/ and rename them
descriptively based on their content"

Categorize project assets:

"Organize @./assets/ into subdirectories:
- icons/
- images/
- fonts/
based on file type and usage"

Image-Based Renaming

Claude can see images and rename them intelligently:

# Before: IMG_1234.png, IMG_1235.png
# After: login-screen.png, dashboard-view.png

"For each image in this directory, view it and rename
with a descriptive name"

Pro Tips

  • Always review proposed changes before approving
  • Use for UI mockup organization
  • Great for cleaning up screenshot folders
  • Can detect duplicates by analyzing content

Tip 15: Compress Conversations with /compact

Quick use-case: When conversations get long, use /compact to compress the history and free up context space while preserving key information.

What is /compact?

The /compact command compresses your conversation history by:

  • Summarizing previous exchanges
  • Removing redundant information
  • Preserving important context and decisions
  • Freeing up context window space

This is Claude Code's equivalent to Gemini CLI's /compress command.

When to Use /compact

Good times to compress:

  • After long debugging sessions with lots of back-and-forth
  • When context window is getting full
  • Before starting a new major feature or topic
  • After completing a major milestone

Example usage:

# Simply type the command
/compact

# Claude will compress the conversation history
# You can continue working with a cleaner context

How It Works

  1. Claude analyzes the entire conversation
  2. Creates a concise summary of key points:
    • Decisions made
    • Problems solved
    • Code patterns established
    • Important context
  3. Replaces the detailed history with the summary
  4. You can continue the conversation normally

What Gets Preserved

  • Key decisions: Architecture choices, patterns adopted
  • Problem solutions: Bugs fixed and their solutions
  • Important facts: Configuration details, requirements
  • Current state: What you're working on, next steps

What Gets Removed

  • Detailed back-and-forth exchanges
  • Redundant questions and answers
  • Exploration paths that didn't work out
  • Verbose explanations that aren't needed anymore

Pro Tips

  • Compress proactively: Don't wait until you hit limits
  • After milestones: Compress after completing features
  • Before branching topics: Compress before switching to a new task
  • Combine with CLAUDE.md: Important facts should still go in CLAUDE.md for persistence
  • Git commits help: Commits serve as compression boundaries

Best Practices

# 1. Complete a feature
"Implement user authentication and commit"

# 2. Compress the conversation
/compact

# 3. Start the next feature with clean context
"Now let's implement the dashboard"

Note: Compression is local to the current session. For truly persistent information, always update CLAUDE.md.


Tip 16: Shell Commands with ! Syntax

Quick use-case: Execute shell commands inline within slash commands and prompts using ! syntax.

Inline Shell Execution

In slash commands, use !command`` to run commands and inject output:

---
description: Show git status
---

# Current Status

!`git status`

!`git log --oneline -5`

What should we work on next?

How It Works

When Claude encounters !command``:

  1. Executes the command
  2. Captures the output
  3. Injects it into the prompt
  4. Claude sees the result before responding

Practical Examples

Commit command:

# Create Commit

<git_diff>
!`git diff --cached`
</git_diff>

Generate a conventional commit message.

Test runner:

# Test Results

!`npm test`

Analyze failures and fix them.

Pro Tips

  • Use for dynamic context injection
  • Perfect for git workflows
  • Combine with $ARGUMENTS for flexible commands
  • Shell commands run in project directory

Tip 17: Leverage All CLI Tools

Quick use-case: Claude can use any command-line tool installed on your system. Your entire toolbox is Claude's toolbox.

What Tools Can Claude Use?

If it's in your $PATH, Claude can use it:

  • Git, Docker, npm, pip
  • ImageMagick, FFmpeg
  • curl, jq, sed, awk
  • Cloud CLIs (AWS, gcloud, etc.)
  • Custom scripts and tools

Examples

Image processing:

"Convert all PNG images to WebP format using ImageMagick"

Media manipulation:

"Use FFmpeg to extract audio from video.mp4"

Cloud operations:

"Deploy this app to AWS using the AWS CLI"

Data processing:

"Use jq to extract all email addresses from this JSON file"

Pro Tips

  • Claude knows common tool syntax
  • It can read --help output if needed
  • Use allowed-tools in slash commands to restrict access
  • Powerful tools require careful approval

Tip 18: Multimodal AI - Images and More

Quick use-case: Claude can see and understand images, not just read code. Use for UI reviews, screenshot debugging, diagram analysis.

Image Capabilities

UI/UX feedback:

"Review this mockup for accessibility: @./design/mockup.png"

Screenshot debugging:

"This error appeared: @./error-screenshot.png
Help me debug it."

OCR and text extraction:

"Extract all text from @./invoice.png and format as JSON"

Design to code:

"Look at @./ui-design.png and generate the React component"

Supported Formats

  • Images: PNG, JPEG, WebP
  • Documents: PDFs (text extraction)
  • Screenshots and mockups
  • Diagrams and charts

Pro Tips

  • Claude can identify UI elements in screenshots
  • Useful for organizing photos by content
  • Can read text from images (OCR)
  • Combine with file organization for smart photo management

Tip 19: Use Hooks for Automation

Quick use-case: Hooks are shell commands that run automatically at specific points in Claude's lifecycle. Use them for formatting, validation, and quality checks.

Available Hook Types

Claude Code supports the following hooks:

  1. PreToolUse - Runs before any tool is executed
  2. PostToolUse - Runs after any tool completes
  3. UserPromptSubmit - Runs when user submits a prompt
  4. SessionStart - Runs when a session begins
  5. SessionEnd - Runs when a session ends
  6. Stop - Runs when user stops Claude
  7. SubagentStop - Runs when a subagent stops
  8. PreCompact - Runs before conversation compaction
  9. PermissionRequest - Runs when permissions are requested
  10. Notification - Runs when notifications are sent

Configuring Hooks

Via settings file:

Edit .claude/settings.json or ~/.claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write {file}"
          },
          {
            "type": "command",
            "command": "eslint --fix {file}"
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "git fetch"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "git status"
          }
        ]
      }
    ]
  }
}

Hook Configuration Format

Each hook has:

  • matcher (optional): Regex pattern to match tool names (e.g., "Write|Edit")
  • hooks: Array of hook configurations
    • type: Usually "command" for shell commands
    • command: The shell command to execute

Common Hook Patterns

Code formatting after file edits:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write {file}"
          }
        ]
      }
    ]
  }
}

Type checking after edits:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "tsc --noEmit {file}"
          }
        ]
      }
    ]
  }
}

Linting before tool execution:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "eslint {file}"
          }
        ]
      }
    ]
  }
}

Session management:

{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Starting Claude Code session'"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "git status"
          }
        ]
      }
    ]
  }
}

Placeholders

Available placeholders in hook commands:

  • {file} - The file path for file-related tools (Write, Edit, etc.)
  • Other tool-specific context may be available

Pro Tips

  • Hooks ensure code quality in auto mode
  • Use matchers to target specific tools (Write, Edit, Bash, etc.)
  • Test hooks manually before enabling
  • Share hooks via git by committing .claude/settings.json
  • Hooks can chain multiple commands in sequence
  • Use PreToolUse for validation, PostToolUse for cleanup/formatting

Tip 20: Prompt Caching with AWS Bedrock

Quick use-case: When using Claude Code with AWS Bedrock as your backend, prompt caching reduces costs by up to 90% and improves latency when you reuse large contexts like codebases, documentation, or conversation history.

⚠️ Important: AWS Bedrock Required

Prompt caching is ONLY available when using AWS Bedrock as the backend for Claude Code. This feature is:

  • NOT available with the default Anthropic API
  • AVAILABLE when configured to use AWS Bedrock
  • Requires AWS account and Bedrock setup

Learn more:

What is Prompt Caching?

Prompt caching allows Claude to reuse previously processed content (like your codebase, system instructions, or conversation history) instead of reprocessing it with every request. This significantly reduces:

  • Cost: Cache hits cost only 10% of normal input token prices (up to 90% savings)
  • Latency: Cached content processes much faster, reducing latency by up to 85%

Setup Requirements

To use prompt caching with Claude Code, you need:

  1. AWS Account with Bedrock access
  2. AWS Bedrock Configuration in Claude Code
  3. Supported Claude models (Opus, Sonnet, Haiku via Bedrock)

How It Works with AWS Bedrock

When configured with AWS Bedrock, Claude Code automatically caches:

  • System instructions and prompts
  • Large file contexts you reference with @
  • Conversation history in extended sessions
  • Tool definitions and MCP server descriptions
  • CLAUDE.md and persistent context

The cache behavior depends on AWS Bedrock's configuration and is automatically managed.

Caching with AWS Bedrock

When you use Claude Code with AWS Bedrock configured, caching works behind the scenes:

# First request - creates cache (with AWS Bedrock backend)
claude -p "Analyze @./large-codebase/"
# Processes all files, writes to cache

# Follow-up requests - uses cache
"Now optimize the authentication module"
# Reads codebase from cache (90% cost reduction)

Note: Caching behavior depends on your AWS Bedrock configuration and region.

When Caching Provides Maximum Value

Best for:

  • 📚 Large codebases: Entire project contexts stay cached
  • 📖 Documentation: Long docs, API references, specifications
  • 💬 Extended conversations: Chat history across multiple turns
  • 🔧 Tool definitions: MCP servers with many tools
  • 📝 System prompts: Complex instructions and examples

Example scenarios:

# Working on a large codebase
claude
"Review the entire @./src/ directory for security issues"
# (Caches the entire src directory)

"Now check for performance bottlenecks"
# (Reuses cached src directory - 90% cheaper, faster response)

"Fix the issues you found"
# (Still using cache if within 5 minutes)

Cache Performance Metrics

While Claude Code handles caching automatically, when using the API directly you can track:

  • cache_read_input_tokens: Tokens retrieved from cache (cheap)
  • cache_creation_input_tokens: Tokens written to cache (25% premium)
  • input_tokens: Regular tokens after cache breakpoint

Example API response:

{
  "usage": {
    "cache_read_input_tokens": 188086, // Read from cache
    "cache_creation_input_tokens": 0, // Nothing new cached
    "input_tokens": 21 // New user message only
  }
}

How AWS Bedrock Optimizes Caching

When using Claude Code with AWS Bedrock, caching is optimized to maximize cache hits:

  1. Stable content first: CLAUDE.md, tool definitions load first
  2. File references cached: When you use @./file, it's cached by Bedrock
  3. Conversation history: Multi-turn chats cache previous context
  4. Automatic invalidation: Cache updates when files change

Note: Specific caching behavior may vary based on your AWS Bedrock configuration.

Cache Invalidation

The cache is invalidated when:

  • Tool definitions change (adding/removing MCP servers)
  • System prompt changes (modifying CLAUDE.md)
  • Referenced files change (editing files you've @ referenced)
  • New user messages (don't invalidate - just add to context)

Minimum Cacheable Size

Content must meet minimum token counts to be cached:

  • 1024 tokens for Opus and Sonnet models
  • 4096 tokens for Haiku 4.5

Smaller contexts won't benefit from caching.

5-Minute vs 1-Hour Cache

5-minute cache (default):

  • Free refreshes when accessed
  • Perfect for active development sessions
  • Best for rapid back-and-forth coding

1-hour cache (premium):

  • 2x the cache write cost
  • Best for less frequent follow-ups (5-60 minute gaps)
  • Useful for long-running agentic tasks
  • Helps with rate limit optimization

Pro Tips for Maximizing Cache Benefits

  1. Keep stable content consistent:

    • Don't modify CLAUDE.md mid-session unnecessarily
    • Reference the same large files across requests
  2. Structure requests efficiently:

    # Good - cache the whole codebase once
    "Review @./src/ for issues"
    "Fix the authentication bugs"
    "Add tests for the fixes"
    
    # Less efficient - different files each time
    "Review @./src/auth.ts"
    "Review @./src/api.ts"
    "Review @./src/utils.ts"
  3. Work in focused sessions:

    • Cache lasts 5 minutes, so stay active
    • Batch related questions together
    • Let cache refresh by staying engaged
  4. Use large contexts fearlessly:

    • Don't hesitate to reference entire directories
    • Include full documentation
    • Load comprehensive examples
  5. Leverage long conversations:

    • Multi-turn debugging sessions benefit most
    • Each turn reuses previous context from cache
    • Cost per message drops dramatically

Caching with Different Claude Code Features

With Skills:

# Skill that references large context

---

## description: Code review with caching

Review all files in @./src/ directory.

# First run caches ./src/

# Subsequent skill runs use cache

With Subagents:

  • Each subagent can benefit from cached context
  • Shared context is cached once, used by all agents

With VS Code Integration:

  • Open files are automatically included in context
  • Context is cached for subsequent requests

When Caching Matters Most

High impact scenarios:

  • 🏗️ Working with codebases >100k tokens
  • 📚 Analyzing multiple documents repeatedly
  • 🔄 Iterative debugging sessions
  • 🤖 Agentic workflows with multiple tool calls
  • 💬 Long conversations with extensive context

Lower impact scenarios:

  • Quick one-off questions
  • Small file edits
  • First-time analysis of new code
  • Infrequent API calls (>5 min apart)

Real-World Example

# Session 1: Analyze large codebase
$ claude
> "Analyze the entire @./src/ directory architecture"
# Cost: $1.50 for 50k tokens (cache write)
# Response time: 3 seconds

> "What security vulnerabilities exist?"
# Cost: $0.15 for 50k cached + 0.05 for new
# Response time: 1 second (cache hit!)

> "Fix the SQL injection issues"
# Cost: $0.15 for 50k cached + 0.05 for new
# Response time: 1 second (cache hit!)

# Total: ~$1.85 instead of $4.50 without caching
# Time saved: 4+ seconds per request

Summary

Prompt caching with AWS Bedrock and Claude Code:

  • ⚠️ Requires AWS Bedrock - not available with default Anthropic API
  • ✅ Saves up to 90% on costs for repeated context
  • ✅ Reduces latency by up to 85%
  • ✅ Perfect for large codebase work
  • ✅ Enables fearless use of comprehensive context

To get started: Configure Claude Code to use AWS Bedrock as your backend. Once configured, caching works automatically based on your Bedrock settings.


Tip 21: /copy Command ❌ NOT AVAILABLE

Status: This feature from Gemini CLI is not currently available in Claude Code.

Gemini equivalent: /copy to copy last response to clipboard.

Claude Code alternative:

  • Select and copy text from terminal
  • Redirect output to files: claude -p "..." > output.txt
  • Use your terminal's copy functionality

Want this feature? There's an active GitHub issue requesting this functionality:


Tip 22: Master Keyboard Shortcuts

Quick use-case: Navigate Claude Code efficiently with keyboard shortcuts.

Essential Shortcuts

Shortcut Action
Esc Toggle auto mode / interrupt operation
Esc + Esc Open rewind menu (see Tip 5)
Shift+Tab Toggle plan mode (extended thinking)
Tab Toggle extended thinking
Ctrl+C Cancel current operation
Ctrl+D Exit Claude Code
Ctrl+L Clear screen
Ctrl+V / Alt+V Paste image from clipboard
Ctrl+R Search command history
/ Show available slash commands
@ Reference files and directories

Multiline Input

Enter multiline prompts using any of these methods:

  • \ + Enter - Backslash to continue on next line
  • Shift+Enter - Continue without submitting
  • Option+Enter - macOS alternative
  • Ctrl+J - Another alternative
  • Direct paste - Paste multiline text directly

Pro Tips

  • Double-tap Esc for quick access to rewind feature
  • Use Shift+Tab to activate plan mode for complex problems
  • Ctrl+L clears screen clutter without losing session
  • Paste images directly with Ctrl+V for multimodal analysis
  • Ctrl+R lets you search and reuse previous commands

Tip 23: Customize with Settings

Quick use-case: Tailor Claude Code's behavior through the settings file for consistent workflows.

Settings File Location

  • Project settings: .claude/settings.json
  • Global settings: ~/.claude/settings.json

Project settings override global settings.

Common Settings

Example settings.json:

{
  "default_model": "sonnet",
  "auto_commit": false,
  "hooks": {
    "before_edit_applied": ["prettier --write {file}"],
    "after_edit_applied": ["npm run typecheck {file}"]
  },
  "allowed_tools": ["Read", "Edit", "Bash"],
  "mcp_servers": {
    "github": {
      "enabled": true
    }
  }
}

Model Selection

{
  "default_model": "sonnet", // or "opus" or "haiku"
  "model_preferences": {
    "complex_tasks": "opus",
    "simple_tasks": "haiku"
  }
}

Pro Tips

  • Commit .claude/settings.json to share team settings
  • Use global settings for personal preferences
  • Override specific settings per project
  • Ask Claude to help configure settings

Tip 24: VS Code Integration

Quick use-case: Use Claude Code directly in VS Code for seamless IDE integration with context awareness.

Setup

Install VS Code extension:

  1. Search for "Claude Code" in VS Code marketplace
  2. Install the official Anthropic extension
  3. Claude Code will automatically detect VS Code integration

Features

Context awareness:

  • Claude sees your open files
  • Knows your cursor position
  • Understands your workspace structure

Diff view:

  • Proposed changes open in VS Code's diff editor
  • Review changes with familiar interface
  • Accept or reject inline

Command palette:

  • Access Claude Code via Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows/Linux)
  • Run commands without leaving the editor

Usage

From integrated terminal:

# Run Claude Code in VS Code's terminal
claude

Side-by-side workflow:

  • Keep Claude Code terminal open
  • View code changes in main editor
  • Use diff view for reviews

Pro Tips

  • Claude automatically uses open files as context
  • Great for Jupyter notebook workflows
  • Works with VS Code's git integration
  • Use @ to explicitly reference files not in your workspace

Tip 25: GitHub Integration

Quick use-case: Automate GitHub workflows - create PRs, review code, manage issues, all through Claude.

Setup GitHub MCP

Add to .mcp.json:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"]
    }
  }
}

Common GitHub Tasks

Create pull request:

"Create a PR for these changes with a descriptive title and summary"
# Claude understands "pr" shorthand

Review PR:

"Review PR #123 and provide feedback"

Fix PR comments:

"Fix all comments on my PR and push updates"

Manage issues:

"Create an issue for this bug with reproduction steps"

GitHub CLI Integration

Claude can use gh CLI if installed:

"Use gh to list my open PRs"
"Close issue #45 with gh"

CI/CD with GitHub Actions

Install GitHub app:

/install-github-app

This enables automatic PR reviews by Claude on every pull request.

Customize review prompt:

Edit claude-code-review.yml:

prompt: |
  Review this PR focusing on:
  - Security vulnerabilities
  - Logic errors
  - Performance issues

  Be concise. Only comment on genuine issues.

Pro Tips

  • Claude generates conventional commit messages automatically
  • Use pr shorthand for pull requests
  • GitHub Actions can run Claude Code in CI
  • Customize review prompts to avoid over-commenting

Tip 26: Use Subagents for Complex Tasks

Quick use-case: Subagents are specialized Claude instances with specific roles and tools. Use them for modular, complex workflows.

What are Subagents?

Subagents are defined Claude instances with:

  • Specific expertise/role
  • Limited tool access
  • Focused context
  • Custom prompts

Creating Subagents

Via CLI flag:

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer",
    "prompt": "You are a senior code reviewer. Focus on security and best practices.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist",
    "prompt": "Expert at finding and fixing bugs",
    "tools": ["Read", "Edit", "Bash"],
    "model": "opus"
  }
}'

Via configuration file:

.claude/agents/reviewer.md:

---
description: Code quality expert
allowed-tools: Read, Grep, Bash(git diff:*)
model: sonnet
---

You are a senior software engineer focused on code quality.
Review code for:

- Security vulnerabilities
- Performance issues
- Code smells
- Best practices

Using Subagents

Delegate to subagents:

"Have the code-reviewer check this file, then the debugger fix any issues"

Subagents in workflows:

.claude/commands/feature-complete.md:

---
description: Complete feature workflow
---

1. Review code with code-reviewer agent
2. Fix issues with debugger agent
3. Generate tests with test-generator agent
4. Create PR with summary

Pro Tips

  • Use subagents for separation of concerns
  • Limit tool access per agent for safety
  • Combine multiple agents in workflows
  • Useful for complex multi-step tasks

Tip 27: Plan Mode for Complex Problems

Quick use-case: For complex features or refactors, use Plan Mode to have Claude create a comprehensive strategy before coding.

What is Plan Mode?

Plan Mode activates Claude's extended thinking capabilities to:

  • Analyze the problem deeply
  • Create detailed implementation plans
  • Break down complex tasks
  • Identify edge cases

Using Plan Mode

Enable during session:

Press Shift+Tab to toggle plan mode on/off, or ask explicitly:

"Use plan mode to design a solution for [complex problem]"

Workflow with Plan Mode:

  1. Research: "Research the best approach for implementing OAuth2"
  2. Plan: "Create a detailed plan for the implementation"
  3. Review: Review the plan, save it if good
  4. Implement: "Implement the plan step by step"
  5. Verify: "Verify the implementation against the plan"

Recommended Workflow

# Step 1: Research
"Research authentication patterns for SaaS apps"

# Step 2: Plan
"Create a detailed implementation plan.
Save it as @./docs/auth-plan.md"

# Step 3: Implement
"Implement the plan from @./docs/auth-plan.md
Verify each step against requirements"

# Step 4: Test
"Write comprehensive tests for the implementation"

# Step 5: PR
"Create a PR with detailed changelog"

Pro Tips

  • Press Shift+Tab to quickly toggle plan mode during your session
  • Use plan mode for unfamiliar problems
  • Save plans as documentation
  • Plans help with code review
  • Can reset to plan if implementation goes wrong
  • Especially useful for refactoring large codebases

Tip 28: Plugins for Extended Functionality

Quick use-case: Plugins are packaged collections of slash commands, subagents, and configurations that extend Claude Code's capabilities.

Installing Plugins

Via plugin marketplace:

/plugin marketplace add <url>
/plugin install <plugin-name>

Example plugins:

  • claude-code-essentials - Core development workflows
  • full-stack-development - Frontend and backend tools
  • security-hardening - Security scanning and auditing
  • data-ml-pipeline - Data science workflows

Popular Plugin Collections

Development workflows:

  • Feature development pipelines
  • Testing frameworks
  • Deployment automation

Code quality:

  • Security scanners
  • Performance analyzers
  • Documentation generators

Infrastructure:

  • Docker optimization
  • Kubernetes manifests
  • CI/CD pipelines

Creating Your Own Plugin

Plugins are structured directories with:

my-plugin/
├── commands/          # Slash commands
├── agents/           # Agent definitions
├── skills/           # Automated workflows
└── plugin.json       # Plugin metadata

Example plugin.json:

{
  "name": "my-dev-workflow",
  "version": "1.0.0",
  "description": "Custom development workflow",
  "commands": ["commit", "pr", "deploy"],
  "subagents": ["reviewer", "tester"]
}

Pro Tips

  • Browse community plugins for inspiration
  • Share plugins with your team
  • Plugins provide turnkey workflows
  • Combine multiple plugins for comprehensive tooling

Summary

Claude Code is a powerful agentic coding assistant that becomes even more capable when you master these techniques:

Core Productivity Tips

  1. Context: Use CLAUDE.md and @ references
  2. Automation: Create slash commands and skills
  3. Integration: Connect MCP servers for external tools
  4. Validation: Set up hooks for code quality
  5. Collaboration: Share configuration via git

Getting Started Checklist

  • Install Claude Code
  • Create CLAUDE.md for your project
  • Set up useful slash commands
  • Configure hooks for code quality
  • Add MCP servers for tools you use
  • Try VS Code integration
  • Experiment with subagents for complex tasks
  • Learn Esc key for reviewing changes
  • Use /compact for long sessions
  • Work with large codebases to benefit from automatic prompt caching

Additional Resources

Contributing

Have additional tips? Share them with the community:

  • Check out Anthropic on GitHub
  • Contribute to the awesome-claude-code repository
  • Share your slash commands and configurations

This guide was adapted from the excellent Gemini CLI tips by Addy Osmani and customized for Claude Code with accurate feature mapping and Claude-specific best practices.

About

Professional tips and tricks for effectively using Claude Code for agentic coding

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published