How Programmers Can Use Claude Code Effectively
Claude Code is Anthropic’s command-line coding assistant. It can understand a repository, execute commands, edit files, and manage Git directly from your terminal—a senior programming partner living alongside your tools. As with any powerful tool, knowing how to use it and using it well are very different things.
This article brings together practical experience from Claude Code creator Boris Cherny, Vue.js creator Evan You, and Google Chrome engineering leader Addy Osmani; insights from Anthropic hackathon winner Affaan Mustafa’s Shorthand Guide and Longform Guide; and the community projects everything-claude-code (50K+ stars) and awesome-claude-skills (38K+ stars).
1. Understand the Core Constraint: the 200K Context Window
Before learning any tricks, understand this: Claude Code’s 200K-token context window is your scarcest resource.
Loading an entire medium-sized, 200-file project can require roughly 800K tokens—four times the available capacity. Intensive work can fill the window in 30 minutes. As it fills, Claude can begin to lose track of earlier instructions and the quality of its output deteriorates.
That is why these practices center on context management.
| Action | Purpose |
|---|---|
/clear |
Clear context between unrelated tasks—the most frequently recommended tip |
/compact <description> |
Compact manually at around 70–80% capacity |
/context |
Audit token usage |
/statusline |
Customize a status line to monitor context consumption |
The guide’s rule of thumb: compact manually at 70–80% rather than waiting for automatic compaction at 95%. Use logical stopping points to manage context deliberately.
2. CLAUDE.md: Your Most Important Configuration File
CLAUDE.md is loaded at the start of each session. Think of it as an onboarding document for your AI partner.
What to Include
# Building the project
- Build: `pnpm build`
- Test: `pnpm test`
- Lint: `pnpm lint:fix`
# Code conventions
- Use TypeScript strict mode.
- Use PascalCase for component names.
- Do not use any; declare types explicitly.
- Use the custom AppError class for error handling.
# Git conventions
- Commit format: `feat/fix/docs(scope): description`
- Branch names: `feature/xxx` or `fix/xxx`
# IMPORTANT: preserve during compaction
Preserve the complete list of modified files and every test command.
What to Leave Out
Avoid standard language conventions Claude can infer, frequently changing information, exhaustive file-by-file descriptions, vague requests such as “write clean code,” and lengthy API documentation. Link to detailed references instead.
Key Principles
- Keep the file within 50–100 lines, or about 2,500 tokens. Long files can cause what Boris calls “rule amnesia.”
- Every rule should earn its place. Would Claude make a mistake without it? If not, remove it.
- Emphasize essential requirements with language such as
IMPORTANT:or “You must.” - Commit the file so the team can maintain it. Boris’s team updates theirs several times a week.
- Add a rule when Claude makes a recurring mistake.
- Import additional files with
@path/to/importinstead of cramming everything into one document.
File Hierarchy
~/.claude/CLAUDE.md # Global: all projects
./CLAUDE.md # Project: shared by the team
./CLAUDE.local.md # Local overrides: gitignored
./src/CLAUDE.md # Subdirectory rules for monorepos
Modular Rules
For larger projects, split concerns into .claude/rules/:
~/.claude/rules/
security.md # No hardcoded secrets; validate inputs
coding-style.md # Immutability and file-size limits
testing.md # TDD workflow and 80% coverage
git-workflow.md # Commit conventions
agents.md # When to delegate
performance.md # Model selection
3. Subagents: Protecting Your Context
Each subagent runs in its own context window, keeping research and intermediate work out of the main conversation.
Evan You’s Advice
Evan recommends assigning fixes to separate subagents, one by one, instead of crowding many fixes into a single session where insufficient context can lead to hallucinations.
The underlying principle is simple: multiple focused contexts are often more effective than one overloaded conversation.
Suggested Architecture
The community guide recommends 13 specialized subagents under .claude/agents/:
- Planning and design:
planner.mdfor complex features and refactoring;architect.mdfor system design. - Quality:
code-reviewer.md,tdd-guide.md, andsecurity-reviewer.md. - Language specialists:
go-reviewer.md,python-reviewer.md, andjava-reviewer.md. - Error handling:
build-error-resolver.mdande2e-runner.mdfor Playwright testing. - Maintenance:
refactor-cleaner.mdanddoc-updater.md.
Example Definition
# .claude/agents/code-reviewer.md
---
name: code-reviewer
description: Review completed implementations for code quality
tools: Read, Grep, Glob
model: opus
---
You are a senior code reviewer. Check:
- Edge cases and error handling
- Performance and memory leaks
- Security vulnerabilities, including injection and XSS
- Readability and maintainability
Iterative Retrieval
Subagents return summaries to save context, but the main agent understands the broader purpose that a literal search query may omit. The main agent should evaluate the result, ask a focused follow-up before accepting it, and send the subagent back to the source when necessary. Repeat up to three cycles.
Give a subagent the goal and its context, not merely a query.
Writer/Reviewer Pattern
Use one session to implement and a fresh session to review. A reviewer with a new context is less likely to assume the implementation must be correct simply because it wrote it.
4. Hooks: Deterministic Automation
Instructions in CLAUDE.md depend on the model following them. Hooks provide deterministic actions at defined points in the workflow.
| Event | Trigger | Example |
|---|---|---|
| PreToolUse | Before a tool runs | Block dangerous commands; remind about tmux |
| PostToolUse | After a tool runs | Formatting; TypeScript checks |
| UserPromptSubmit | When a message is sent | Inspect user input |
| Stop | When Claude finishes responding | Save state; detect console.log |
| PreCompact | Before context compaction | Preserve important context |
| Notification | When permission is requested | Send a system notification |
Example Configuration
{
"hooks": {
"PostToolUse": [
{"matcher": "Write|Edit", "hooks": [{"type": "command", "command": "npx prettier --write $CLAUDE_FILE_PATH || true"}]},
{"matcher": "Edit && .ts/.tsx", "hooks": [{"type": "command", "command": "npx tsc --noEmit || true"}]}
],
"PreToolUse": [
{"matcher": "Bash && (npm|pnpm|yarn|cargo|pytest)", "hooks": [{"type": "command", "command": "if [ -z \"$TMUX\" ]; then echo '[Hook] Consider running long commands in tmux' >&2; fi"}]},
{"matcher": "Write && .md", "hooks": [{"type": "command", "command": "node .claude/hooks/block-non-readme-md.js"}]}
],
"Stop": [
{"matcher": "*", "hooks": [{"type": "command", "command": "node .claude/hooks/check-console-log.js"}]}
]
}
}
Persist lessons with a Stop hook, which runs at the end, rather than UserPromptSubmit, which runs on every message and adds latency. For a conversational approach, run /hookify and describe the desired behavior.
5. Context and Memory Across Sessions
Session Memory Files
Use a .tmp file under .claude/ to track progress:
# .claude/session-state.tmp
## Verified approaches
- Replacing Webpack with Vite reduced builds from 45s to 8s.
- JWT plus refresh-token authentication passed security review.
## Attempted approaches that failed
- Direct esbuild bundling did not support CSS Modules; abandoned.
- Redis caching introduced a race condition; reverted.
## Not yet attempted
- Server-side rendering optimization
- Database index optimization
Dynamic System Context
Instead of placing everything in CLAUDE.md, inject context through CLI flags:
claude --system-prompt "$(cat memory.md)"
System instructions take precedence over user messages, which take precedence over tool output. This provides a way to control which context is loaded.
alias claude-dev='claude --system-prompt "$(cat ~/.claude/contexts/dev.md)"'
alias claude-review='claude --system-prompt "$(cat ~/.claude/contexts/review.md)"'
alias claude-research='claude --system-prompt "$(cat ~/.claude/contexts/research.md)"'
Persistence Hooks
Three useful hooks cover the lifecycle: PreCompact saves critical state before compression; Stop saves lessons at the end; SessionStart reloads prior context.
When Claude discovers a nontrivial debugging technique, workaround, or project pattern, capture it as a Skill. Similar future tasks can reuse it without rediscovering the same solution.
6. Token Optimization: Cost and Efficiency
Model Selection
The source guide argues that Sonnet is sufficient for roughly 90% of coding tasks rather than using the most expensive model for everything.
| Task | Suggested model | Reason |
|---|---|---|
| File exploration and search | Haiku | Speed and cost |
| Simple single-file edits | Haiku | Clear, narrow instructions |
| Multi-file implementation | Sonnet | Balanced coding performance |
| PR review | Sonnet | Context understanding and subtle issues |
| Documentation | Haiku | Straightforward structured output |
| Complex architecture | Opus | Deep reasoning |
| Security analysis | Opus | Avoid missing vulnerabilities |
| Systemic debugging | Opus | Broad system context |
Signals to move to Opus include Sonnet failing on the first attempt, a task spanning five or more files, architecture decisions, and security-critical code. Use /model sonnet normally and /model opus when needed.
Suggested Configuration
{
"model": "sonnet",
"MAX_THINKING_TOKENS": "10000",
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50"
}
The guide estimates around 60% savings from making Sonnet the default. It also suggests limiting thinking to 10,000 tokens instead of 31,999 and compacting automatically at 50% capacity.
Tool Choices
The source recommends mgrep in place of grep/ripgrep, estimating approximately 50% fewer tokens; keeping files in the hundreds rather than thousands of lines; and limiting reads with --lines, estimating about 70% savings for a 400-line file.
Many MCP servers wrap existing CLIs. A /gh-pr command around gh pr create, or a Skill using the Supabase CLI, can replace a corresponding MCP integration. Every unused MCP server you disable frees context.
7. Workflow Practices
Four Phases
Explore → Plan → Implement → Verify
- Enter Plan Mode with
Shift+Tab. Read code and answer questions without changes. - Request a detailed plan and review it in an editor with
Ctrl+G. - Return to Normal Mode to implement and self-check.
- Run tests, builds, and lint checks.
The source reports roughly 45% fewer architecture mistakes when using Plan Mode for multi-file changes.
The Verification Loop
The strongest common recommendation across the sources is to give Claude a way to verify its own work. They describe a two- to threefold improvement in final quality.
Verification can include test suites, builds and type checks, lint and formatting, UI screenshot comparisons, and end-to-end tests.
# Example verification rule in CLAUDE.md
After changing code, run `pnpm test` and `pnpm build` and resolve failures.
Evaluation Measures
pass@k: at least one successful attempt in k trials
k=1: 70% k=3: 91% k=5: 97%
pass^k: every attempt must succeed
k=1: 70% k=3: 34% k=5: 17%
Use pass@k when you need a task to work once; use pass^k when consistency matters.
Five Stages for Complex Tasks
Research (Explore agent) → research-summary.md
Planning (Planner agent) → plan.md
Implementation (TDD-guide agent) → code changes
Review (Code-reviewer agent) → review-comments.md
Verification (Build-error-resolver) → finish or repeat
Each stage receives a clear input and produces a clear output for the next. Do not skip stages; clear context between stages and preserve intermediate results in files.
8. Parallel Work
Boris Cherny’s Setup
Boris describes five local terminal sessions, numbered 1–5, alongside five to ten web sessions at claude.ai/code. Each local session uses an independent Git checkout, rather than sharing a branch or worktree. System notifications indicate when input is needed; --teleport transfers work between local and web environments. He also starts sessions from his phone in the morning.
Parallel Strategies
Use /fork for non-overlapping work: keep implementation in the main session while a fork answers repository questions, checks status, or researches services.
For overlapping changes, create separate Git worktrees:
git worktree add ../project-feature-a feature-a
git worktree add ../project-feature-b feature-b
cd ../project-feature-a && claude
The Cascade approach opens new tasks in tabs to the right, handles them from oldest to newest, and caps parallel work at three or four tasks. Use only as much parallelism as the work needs.
Starting a New Project with Two Instances
A scaffolding agent creates project structure and configuration such as CLAUDE.md, rules, and agents. A research agent connects services, searches references, develops a detailed PRD, creates Mermaid architecture diagrams, and compiles documentation.
9. Skills and Commands: Reusable Workflows
Skills in ~/.claude/skills/ define broader workflows that activate according to the task. Commands in ~/.claude/commands/ are prompts invoked with slash commands.
~/.claude/skills/
pmx-guidelines.md # Project patterns
coding-standards.md # Language practices
tdd-workflow/ # Multi-file Skill
security-review/ # Checklist Skill
~/.claude/commands/
commit-push-pr.md # Used frequently by Boris
refactor-clean.md # Remove dead code after long sessions
deploy-check.md # Predeployment checks
Codemaps
A codemap lets Claude navigate without spending context rediscovering the repository:
# .claude/skills/project-map.md
## Code map
- `src/api/` — REST endpoints
- `src/services/` — Business logic
- `src/models/` — Database models
- `src/middleware/` — Express authentication and error handling
- `tests/` — Tests mirroring the src structure
Community Skills
awesome-claude-skills collects more than 150 Skills:
| Category | Count | Examples |
|---|---|---|
| Development tools | 19 | Code quality, Playwright, MCP server development |
| Documents | 5 | Word, PDF, PowerPoint, Excel |
| Data analysis | 4 | CSV summaries, PostgreSQL, root-cause analysis |
| Security | 4 | Digital forensics, threat hunting, metadata extraction |
| Creative media | 6 | Canvas design, image enhancement, GIF creation |
| Productivity | 8 | File organization, invoices, tailored résumés |
| App automation | 78+ | Composio integrations with 1,000+ apps including HubSpot, Jira, Slack, and GitHub |
Installation
mkdir -p ~/.config/claude-code/skills/
# Copy Skill folders into this directory, then start Claude Code.
# Alternatively, use the plugin marketplace:
/plugin marketplace add affaan-m/everything-claude-code
/plugin install everything-claude-code@everything-claude-code
10. MCP Servers: Connecting External Tools
The Model Context Protocol connects Claude Code to tools and services. It is a prompt-driven interface around APIs, rather than a replacement for APIs.
Example Configuration
{
"github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"] },
"firecrawl": { "command": "npx", "args": ["-y", "firecrawl-mcp"] },
"supabase": { "command": "npx", "args": ["-y", "@supabase/mcp-server-supabase@latest"] },
"memory": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"] },
"sequential-thinking": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] },
"vercel": { "type": "http", "url": "https://mcp.vercel.com" },
"context7": { "command": "npx", "args": ["-y", "@context7/mcp-server"] }
}
Too many enabled tools can leave only 70K tokens of a nominal 200K context window available for work. Configure 20–30 integrations if needed, but keep fewer than ten servers and 80 tools active at once. Tool descriptions consume context. Use /mcp to inspect and toggle them, and consider CLI-based Skills when the service has a CLI such as gh, supabase, or vercel.
11. Plugins: Packaged Toolkits
Plugins bundle Skills, MCP integrations, hooks, and tools to reduce manual setup.
claude plugin marketplace add https://github.com/mixedbread-ai/mgrep
# Manage plugins inside Claude with /plugins.
| Plugin | Purpose |
|---|---|
| typescript-lsp | TypeScript intelligence outside the editor |
| pyright-lsp | Python type checking |
| hookify | Create hooks conversationally |
| mgrep | Search with an estimated 50% token saving |
| frontend-design | UI and UX patterns |
| commit-commands | Git workflow automation |
| context7 | Current documentation lookup |
As with MCP, keep only four or five plugins active and monitor context usage. Language Server Protocol plugins are especially useful outside an IDE, providing live type checking, navigation, and completion.
12. Working with an Editor
Zed
The community recommends Zed for its Rust-based speed, fast startup, responsiveness in large repositories, and modest resource usage. It can keep up with rapid AI edits, show changes in the Agent Panel, expose custom slash commands with CMD+Shift+R, and avoid competing heavily for CPU and RAM.
General Tips
Use a split view with terminal and editor side by side. Ctrl+G opens Claude’s current work in the editor. Enable autosave so Claude reads current files, and ensure the editor automatically reloads external changes.
Voice Input
Transcription can be faster than typing. On macOS, examples include superwhisper and MacWhisper. Claude can often infer intent despite minor transcription errors.
13. Common Pitfalls
Kitchen-Sink Sessions
Mixing unrelated questions into an implementation session fills the context with irrelevant information. Clear context between unrelated tasks, including when moving from a completed feature to a separate bug fix.
Repeated Corrections
After two unsuccessful corrections, clear the session and rewrite the initial prompt using what you learned. Otherwise failed attempts accumulate in context.
Bloated CLAUDE.md
A 500-line instruction file can bury its important rules. Remove instructions Claude does not need, or make deterministic requirements hooks.
Loading the Entire Project
Two hundred files may cost around 800K tokens. Target three to five relevant files instead of indiscriminately loading 50.
Skipping Planning
Immediate coding can solve the wrong problem. The guide recommends Plan Mode for changes affecting more than three files.
Unbounded Exploration
An open-ended “investigate this” can result in hundreds of file reads. Bound the investigation or give it a separate subagent context.
Casual Use of Permission Bypass
The source reports that 23% of users who experienced destructive execution had enabled --dangerously-skip-permissions. Prefer allowlisting safe commands through /permissions; reserve skipped permissions for containers without network access.
14. Keyboard and Command Reference
| Shortcut | Action |
|---|---|
| Ctrl+U | Delete the entire input line |
| Shift+Enter | Enter multiple lines |
| Shift+Tab | Switch modes |
| Esc Esc | Interrupt Claude or restore code |
| @ | Search files |
| / | Open slash commands |
| ! | Run a Bash command quickly |
| Ctrl+G | Edit in the editor |
| Tab | Toggle thinking display |
| Command | Purpose |
|---|---|
| /clear | Clear context |
| /compact | Compact manually |
| /context | Audit token usage |
| /fork | Branch a session |
| /model | Switch models |
| /rewind | Return to a previous state |
| /checkpoints | File-level restore points |
| /statusline | Customize the status line |
| /mcp | Manage MCP servers |
| /plugins | Manage plugins |
| /rename | Name a conversation |
alias c='claude'
alias cc='claude --continue' # Continue the last session
15. AI Research from Data Preparation to Publication
With Hugging Face Skills, Claude Code can support more than application development: it can coordinate the full AI research workflow.
Installation
/plugin marketplace add huggingface/skills
/plugin install hugging-face-model-trainer@huggingface/skills
/plugin install hugging-face-trackio@huggingface/skills
# Install other Skills as needed.
Nine Research Skills
| Skill | Purpose | Research value |
|---|---|---|
| Model Trainer | Train and fine-tune with TRL: SFT, DPO, GRPO, reward modeling | Reproducible training, hardware selection, cost estimation, GGUF conversion for local deployment |
| Trackio | Live training metrics and dashboards | Experiment tracking, ablations, shared dashboards on HF Spaces |
| Evaluation | Evaluation and benchmark management | Import Artificial Analysis scores; run custom vLLM/lighteval evaluations |
| Datasets | Create and manage Hub datasets | Benchmarks, training corpora, SQL queries and transformations |
| Paper Publisher | Publish research on the Hub | Link papers, models, datasets, and code for discoverability and reproducibility |
| Gradio | Interactive web demos | Let readers and reviewers try the model |
| Jobs | Run cloud compute on HF infrastructure | Large-scale training and evaluation without owning GPUs |
| HF CLI | Upload and download models and datasets | Simplify pipelines and distribution |
| Tool Builder | Reusable API automation scripts | Reproducible preprocessing pipelines |
Example Workflow
1. Prepare data
“Use the HF Datasets Skill to create an instruction-tuning dataset
from the JSONL files in my data/ directory.”
2. Fine-tune
“Use Model Trainer to SFT fine-tune Qwen2.5-7B on that dataset
and estimate the A100 cost.”
3. Track experiments
“Use Trackio to record loss, learning rate, and evaluation metrics,
and sync the dashboard to my HF Space.”
4. Evaluate
“Evaluate the model on MMLU, HumanEval, and my custom benchmark.
Compare it with the baseline in a results table.”
5. Build a demo
“Create a conversational Gradio demo and deploy it to HF Spaces.”
6. Publish
“Create a paper page on the HF Hub with Paper Publisher,
linking the trained model, dataset, and demo.”
Why Researchers Should Care
Skills produce versionable code and configuration, helping reviewers reproduce experiments. Papers, models, data, and code can form one connected collection on the Hub. Cloud jobs lower the hardware barrier and include cost estimation. Trackio dashboards support shared experiment monitoring. These Skills also support Cursor, Codex CLI, and Gemini CLI as well as Claude Code.
The result is a research workflow that can be coordinated through natural-language requests in a terminal, with generated code and reproducible artifacts.
16. Security Practices
Every integration creates another possible entry point.
Sandboxing and Access
Restrict allowedTools to necessary capabilities. Deny access to sensitive locations such as ~/.ssh, ~/.aws, and credential files. Run untrusted repositories in Docker with --network=none.
Protecting Data
Treat external content as potentially influential input: validate it, audit external links in configuration and Skills, and consider including vetted documentation directly instead of depending on mutable external sources.
Memory Poisoning
Audit persistent files regularly, because malicious instructions can accumulate across sessions.
AgentShield
The guide recommends npx ecc-agentshield scan, covering 102 security rules, for automated scanning.
Closing Thoughts
Claude Code is more than completion software. It is a capable collaborator whose context and workflow need to be managed.
| Practice | Intended benefit |
|---|---|
| Provide tests, screenshots, and builds | Two- to threefold quality improvement reported by the sources |
| Clear unrelated context | Avoid contamination |
| Plan multi-file changes | Around 45% fewer architecture mistakes reported |
| Keep CLAUDE.md under 100 lines | Reduce rule amnesia |
| Research with subagents | Protect the main context |
| Compact at 70–80% | Avoid degradation |
| Separate Git checkouts for parallel sessions | Increase throughput |
| Format with PostToolUse hooks | Consistent automation |
| Disable unused MCP servers | Reclaim context |
| Restart after two failed corrections | Avoid accumulating unsuccessful approaches |
Affaan Mustafa describes the effort of building reusable workflows as an investment that compounds as models and agent tools improve. These principles can turn an occasionally useful assistant into a dependable programming partner.