Claude Code Best Practices: From 'Usable' to 'Truly Useful'

@PandaTalk8
SIMPLIFIED CHINESE4 months ago · Mar 23, 2026
503K
1.6K
368
42
3.6K

TL;DR

A comprehensive guide to mastering Claude Code, covering essential features like CLAUDE.md configuration, Plan Mode for architecture, and effective context management to maximize AI productivity.

I've been using Claude Code for over half a year, and I've stepped into more pitfalls than I've written lines of code.

Initially, I thought Claude Code was just a "more advanced Copilot"—type in the terminal, it writes code, and you're done. Later, I realized that the ceiling for this tool is much higher than I imagined, but only if you know how to use it.

This article combines official documentation and practical experience to organize what I believe are the most important usage tips. Some are lessons learned the hard way, while others are hidden features I only discovered by reading the docs.

1. CLAUDE.MD: The Most Underrated Feature

If you only remember one thing from this article, remember this: Write your CLAUDE.md well.

CLAUDE.md is the instruction file that Claude Code automatically reads at the start of every conversation. It's like an onboarding doc you write for a new colleague—whatever you want them to know, you write it there.

Many people don't write a CLAUDE.md or just write a couple of lines. The result is having to explain the project structure, coding standards, and tech stack choices from scratch in every conversation. It's like re-introducing the company to your colleague every single morning.

What a good CLAUDE.md should include:

markdown
1# Project Name
2
3## Build and Test Commands
4- Install dependencies: npm install
5- Run tests: npm test
6- Single test: npm test -- --grep "test name"
7- Formatting: npm run format
8
9## Coding Standards
10- Python: Use ruff for formatting, line width 88
11- Testing: Use pytest, one test file per service
12- API Routes: Use plural filenames: users.py, orders.py
13- Commit messages: English, format: type(scope): description
14
15## Architecture Decisions
16- Choose Tailwind over CSS Modules because the team standardized on it
17- User permission checks are done in middleware; don't repeat in every route
18- Redis cache key prefix: app:v1:
19
20## Common Pitfalls
21- DB connection pool limit is 20; don't open new connections in loops
22- Don't mock the database; last time mocks passed but production migration failed

Key principles:

First, write things Claude cannot infer from the code. The "why" of a project is more important than the "what." You don't need to explain how to use React, but you do need to tell it "we chose Tailwind because the team standardized on it."

Second, keep it under 200 lines. The official docs explicitly mention that if CLAUDE.md is too long, Claude might ignore rules. Use markdown headers and lists to keep it scannable.

Third, don't put frequently changing content. Detailed API docs or file-by-file descriptions don't belong in CLAUDE.md. Just provide links.

The Four Levels of CLAUDE.md

Claude Code supports four levels of CLAUDE.md, ordered from highest to lowest priority:

Mr Panda - inline image

In my global CLAUDE.md, I usually write:

text
1- I am a full-stack engineer; no need to over-explain basic concepts
2- Keep replies concise; skip unnecessary pleasantries
3- Don't summarize what you did after code changes; I will check the diff
4- Prioritize simple solutions; avoid over-engineering

These four lines can save you hundreds of repetitive corrections.

Advanced: Organize rules with .claude/rules/

As a project grows, one CLAUDE.md file won't hold everything. The official solution is more elegant: Split rules into the .claude/rules/ directory.

text
1.claude/rules/
2├── testing.md # Testing standards
3├── api-style.md # API writing style
4└── frontend.md # Frontend conventions

Even more powerful, you can use YAML frontmatter to limit rules to specific files:

text
1---
2paths: ["src/api/**/*.ts", "src/routes/**/*.ts"]
3---
4
5API routes must include input validation and error handling.
6All new endpoints require integration tests in tests/api/.

This way, the rule only loads when Claude accesses matching files, saving context space.

2. Prompt Quality Determines Output Quality

This sounds like a cliché, but I've seen too many people use Claude Code like this:

"Help me write a login feature"

Then they worry over a huge chunk of generated code—this isn't what I wanted.

A good instruction should contain three elements: Goal, Constraints, and Context.

Bad Instruction vs. Good Instruction

Bad: "Add a search feature to the user list"

Good: "Add a search box above the table in @src/pages/UserList.tsx. Search should use the backend API /api/users?search=xxx, no frontend filtering. Use a 300ms debounce, and keep the style consistent with the existing Filter component."

The difference? Good instructions reduce ambiguity. Claude Code doesn't have to guess if you want frontend or backend search, the debounce time, or the styling standards.

Official Recommended Prompting Tips

1. Use @ to reference specific files

Claude Code supports using @filepath to pull file content directly into the context. Instead of saying "that auth-related code," writing @src/auth/login.ts is much more precise. You can even specify line ranges: @src/auth/login.ts#5-30.

2. Paste screenshots and images

Use Ctrl+V to paste images directly. When debugging UI issues, a screenshot of "how it looks now" vs "how I want it" is ten times more effective than a text description.

3. Provide validation criteria

Don't just say "help me fix this bug," say:

"Fix the issue where re-authentication fails after a login timeout. After the fix, clicking any button after token expiration should automatically redirect to the login page. Test cases are in @tests/auth.test.ts; run them to confirm they pass after the fix."

Give Claude a self-verifiable standard—test cases, screenshots, expected output—so it can check its own work quality and reduce back-and-forth.

4. Be clear about what NOT to do

Claude Code can sometimes be over-eager—you ask it to fix a bug, and it refactors the surrounding code too. Explicitly saying "only change this function, don't touch other code" saves a lot of trouble.

When vague instructions are useful

Not every situation requires precision. Vague instructions are actually better for exploratory tasks:

  • "What can be improved in this file?"
  • "Help me understand the architecture of this module"
  • "Are there any potential issues with this code?"

But once you reach the implementation stage, switch back to precision mode.

3. PLAN MODE: Think Clearly Before Acting

Claude Code has a Plan Mode, which I consider the most underrated workflow.

How to enter Plan Mode

Three ways:

text
1# Start directly in plan mode
2claude --permission-mode plan
3
4# Switch during conversation (press Shift+Tab twice)
5Shift+Tab Shift+Tab
6
7# Say in the prompt
8"Don't change the code yet, help me make a plan"

In Plan Mode, Claude Code can only read files and search code; it cannot make any modifications. It explores the codebase, analyzes your requirements, and provides a detailed implementation plan.

Correct way to use Plan Mode

Key operation: Press Ctrl+G to open and edit the plan in your editor.

This means you can:

  1. Let Claude generate an initial plan
  2. Ctrl+G to open the plan, delete parts you disagree with, and add your own ideas
  3. Switch back to normal mode (Shift+Tab) and let Claude execute according to the modified plan

Changing a plan takes one sentence; changing already written code takes ten times longer.

Recommended workflow for complex tasks

The official standard process is four steps: Explore → Plan → Implement → Verify.

text
11. Enter Plan Mode
22. Have Claude read relevant code: "Read the code in src/auth/ to understand session logic"
33. Request a plan: "Develop an OAuth2 migration plan"
44. Ctrl+G to review and edit the plan
55. Switch back to normal mode
66. "Implement according to the plan, run tests after writing"
77. Have Claude self-check against requirements

When you don't need Plan Mode

  • Changing a variable name
  • Fixing an obvious typo
  • Adding a single log line

The criteria is simple: If there is only one way to implement the task, do it directly. If there are multiple choices, plan first.

4. SUB-AGENTS: The Multi-tasking Power of Claude Code

Sub-agents are a powerful mechanism—Claude Code can launch independent AI processes to handle tasks in parallel. Each sub-agent has its own context window and won't clutter your main conversation.

Built-in Sub-agent Types

The biggest value of Sub-agents: Context Isolation

When you ask Claude to run tests, analyze logs, or search many files, these operations generate massive output that fills your context window. Use sub-agents for these tasks; the output stays in the sub-agent's context, and only a summary is returned to you.

For example:

"Use a sub-agent to run all tests and list the failed cases"

"Use a sub-agent to search for all files using deprecated APIs"

Running in the background: Ctrl+B

Press Ctrl+B to put a sub-agent in the background. You can continue chatting with Claude about other things, and you'll be notified when the background task completes.

Suitable for:

  • Running test suites (usually takes minutes)
  • Large-scale code searches
  • Non-urgent code reviews

Custom Sub-agents

You can create custom agents in the .claude/agents/ directory:

text
1---
2name: code-reviewer
3description: Code review expert. Triggered automatically after code changes.
4tools: Read, Grep, Glob, Bash
5model: sonnet
6---
7
8You are a senior code reviewer. Check the following dimensions:
9- Code clarity and readability
10- Completeness of error handling
11- Exposure of sensitive information
12- Input validation
13- Performance pitfalls

Then call it in conversation using @"code-reviewer (agent)".

5. Context Management: The Most Overlooked Key

While Claude Code's context window is large (up to 1M tokens), it is not infinite, and context management directly determines output quality.

What's in the context?

  • Your conversation history
  • All file contents read by Claude
  • Command execution output
  • CLAUDE.md file (loaded every time)
  • Memory file (first 200 lines)
  • Loaded Skill and MCP tool definitions

Five Practical Strategies

1. /clear: Clear when a task is done

Don't fix bugs, add features, and refactor all in the same conversation. /clear empties the context but keeps CLAUDE.md, acting like a free restart.

2. /compact: Manually compress context

When the conversation gets long, use /compact to let Claude automatically summarize and compress previous dialogue. A better way is to add a focus to the compression:

/compact focus on API changes and test results

This way, Claude prioritizes keeping the content you care about during compression.

3. /context: See what's eating your context

Type /context to see current usage—which files take up how many tokens and how much space MCP tool definitions occupy. I often find useless MCP servers taking up massive space.

4. Use Sub-agents to isolate noise

Running tests and analyzing logs produces a lot of output. Let sub-agents do it to keep the main conversation context clean.

5. Write compression retention instructions in CLAUDE.md

You can tell Claude what must be kept during compression:

text
1# Compression Instructions
2When compressing context, always keep:
3- Full list of modified files
4- Test commands and results
5- Key architecture decisions

Memory vs CLAUDE.md

Mr Panda - inline image

What Memory is for: Your preferences ("this person likes concise replies"), project conventions ("deployment has a special step"), historical decisions ("we chose option A last time because of X").

What Memory is NOT for: Code details, Git history, temporary states—these are more accurately retrieved from code and Git.

Use the /memory command to view and manage all loaded Memory.

6. Permission Management: Balancing Security and Efficiency

Claude Code provides five permission modes, cycled via Shift+Tab in conversation:

Mr Panda - inline image

Permission Rule Configuration

In .claude/settings.json, you can finely control permissions for each tool:

text
1{
2 "permissions": {
3 "allow": [
4 "Bash(npm run *)",
5 "Bash(git commit *)",
6 "Edit(src/**/*.ts)",
7 "Read(*.md)"
8 ],
9 "deny": [
10 "Bash(rm -rf *)",
11 "Edit(.env)"
12 ]
13 }
14}

Rule priority: deny → ask → allow (deny has the highest priority).

This means you can boldly allow common commands while using deny to protect sensitive files. For example, .env files should never be edited.

Hierarchy of Setting Files

Similar to CLAUDE.md, settings have multiple levels:

text
1Organization Policy (Highest Priority)
2
3CLI Arguments
4
5.claude/settings.local.json (Local, not committed to Git)
6
7.claude/settings.json (Project level, shared with team)
8
9~/.claude/settings.json (Global, personal)
10
11Default Values (Lowest Priority)

My advice: Put team-shared rules in .claude/settings.json, personal preferences in ~/.claude/settings.json, and sensitive configs in .claude/settings.local.json (remember to add to .gitignore).

7. HOOKS: Turning Rules into Iron Laws

Instructions in CLAUDE.md are "suggestions"—Claude follows them most of the time but occasionally forgets. Hooks are "iron laws"—they execute no matter what.

Hooks are shell commands automatically triggered by specific lifecycle events, configured in settings.json.

Key Event Types

Mr Panda - inline image

Practical Examples

Auto-formatting—Run Prettier after every edit:

text
1{
2 "hooks": {
3 "PostToolUse": [{
4 "matcher": "Edit|Write",
5 "hooks": [{
6 "type": "command",
7 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
8 }]
9 }]
10 }
11}

Protecting critical files—Prevent modifying production configs:

text
1{
2 "hooks": {
3 "PreToolUse": [{
4 "matcher": "Edit|Write",
5 "hooks": [{
6 "type": "command",
7 "command": ".claude/hooks/protect-files.sh"
8 }]
9 }]
10 }
11}

A hook command returning exit code 0 means allowed; exit code 2 means blocked. This means you can write any complex logic.

Re-injecting key info after context compression:

text
1{
2 "hooks": {
3 "SessionStart": [{
4 "matcher": "compact",
5 "hooks": [{
6 "type": "command",
7 "command": "echo 'Use Bun, not npm. Run bun test before committing.'"
8 }]
9 }]
10 }
11}

This solves a common pain point: when a long conversation is compressed, important instructions mentioned earlier might be lost. Hooks can automatically re-inject them after every compression.

Four Types of Hooks

8. GIT WORKFLOW: Making Good Use of WORKTREE

Claude Code can execute Git commands, which is a double-edged sword. But the official tool provides a great safety net: Worktree.

Git Worktree: Isolated Workspaces

text
1# Start Claude in an isolated worktree
2claude --worktree feature-auth
3claude --worktree bugfix-123
4
5# Automatically generate a name
6claude --worktree

Worktree creates an independent Git branch copy under .claude/worktrees/. Whatever Claude does inside won't affect your main branch. Upon exit:

  • If no changes → Auto-clean
  • If changes exist → Prompts you to keep or delete

This is especially useful for exploratory tasks. Not sure if a refactoring plan will work? Try it in a worktree; if it fails, throw it away with zero risk.

A few Git Iron Laws

1. Never let Claude Code auto-push

It can commit, but the push action should be confirmed by you. Once pushed to remote, the cost of rolling back increases significantly.

2. Commit frequently

Commit after finishing a small feature. Use /rewind to go back to any checkpoint, provided you have commit records.

3. Beware of destructive operations

If Claude Code wants to execute git reset --hard, git push --force, or rm -rf, think through the consequences before approving. These operations have no undo. You can also deny these commands in permission rules.

4. Restore context from a PR

This automatically loads PR changes and discussions as context, perfect for code reviews or continuing someone else's work.

text
1claude --from-pr 123

9. Shortcuts and Command Reference

I use these shortcuts every day; I highly recommend memorizing them:

Most Common Shortcuts

Mr Panda - inline image

Most Common Slash Commands

text
1/compact [focus] # Compress context, can specify focus
2/clear # Clear conversation, start over
3/context # View context usage
4/memory # View and manage Memory
5/rewind # Roll back to a checkpoint
6/resume [name] # Resume a previous conversation
7/model # Switch models
8/effort [level] # Set reasoning depth: low/medium/high/max
9/init # Auto-generate CLAUDE.md
10/mcp # Manage MCP servers
11/permissions # View permission rules
12/cost # View token consumption

/init is particularly useful for new projects—it automatically analyzes your codebase and helps generate a draft CLAUDE.md. While it usually needs manual adjustment, it's much faster than starting from scratch.

10. EXTENDED THINKING: Let Claude Think Deeper

For complex problems, you can enable Extended Thinking mode, allowing Claude to spend more time reasoning before answering.

How to use it

text
1# Shortcut toggle
2Option+T (Mac) / Alt+T (Windows/Linux)
3
4# Or via command
5/effort high # Deeper reasoning
6/effort max # Maximum reasoning depth
7/effort low # Simple tasks, saves tokens

When to use it

  • Complex architecture decisions
  • Tricky debugging (multiple possible causes to eliminate)
  • Multi-step refactoring design
  • Weighing pros and cons of multiple solutions

When you don't need it

  • Simple code changes
  • Formatting, renaming
  • Already clear bug fixes

Pro-tip: Writing "ultrathink" in the prompt can force the highest reasoning depth without manually adjusting effort settings.

11. MCP SERVER: Connecting Claude to the Outside World

MCP (Model Context Protocol) allows Claude Code to communicate with external tools—GitHub, databases, Slack, Notion, etc.

Quick Add

text
1claude mcp add github -- npx @anthropic-ai/mcp-server-github
2claude mcp add postgres -- npx @anthropic-ai/mcp-server-postgres postgresql://localhost:5432/mydb

Configuration File

MCP is configured in .mcp.json:

text
1{
2 "mcpServers": {
3 "github": {
4 "type": "stdio",
5 "command": "npx",
6 "args": ["@modelcontextprotocol/server-github"],
7 "env": {
8 "GITHUB_TOKEN": "$GITHUB_TOKEN"
9 }
10 }
11 }
12}

Note Context Overhead

Each MCP server consumes an additional 100-500+ tokens for tool definitions. Use the /mcp command to check the overhead of each server and disable unused ones.

My experience: Don't be greedy. 2-3 commonly used MCP servers are enough. Installing too many eats up context space with tool definitions, which can actually degrade code analysis quality.

12. IDE Integration: More Than Just a Terminal

VS Code

After installing the Claude Code extension, you can use Claude directly in VS Code without switching to the terminal.

Useful features:

  • Side-by-side diff view: Claude's changes are shown as diffs, clear at a glance
  • Option+K / Alt+K: Quickly insert @references to the current file
  • Multi-tab conversations: Open multiple independent conversations in different tabs
  • Cmd+Shift+Esc: Quickly open a new conversation tab

JetBrains

IntelliJ, PyCharm, WebStorm, and other JetBrains IDEs also have a Claude Code plugin. Just search for "Claude Code" in the Plugins marketplace to install.

13. Reviewing Code: Trust but Verify

Claude Code's code quality is generally good, but you shouldn't trust it blindly.

Common Issues

1. Over-engineering

You ask for a simple utility function, and it gives you a full abstraction layer with generics, interfaces, and factory patterns. Using a sledgehammer to crack a nut.

Solution: Write "prioritize simple solutions" in CLAUDE.md, or explicitly say "no abstraction needed" in the instruction.

2. Hallucinated APIs

It sometimes uses non-existent APIs or outdated syntax, especially for new versions of niche libraries.

Solution: Run tests. This is why instructions should include validation standards.

3. Scope Creep

You ask it to change one function, and it refactors the whole file.

Solution: Explicitly say "only change X, don't touch other code." Or use the /freeze command to limit editing scope to specific directories.

Writer/Reviewer Mode

An advanced mode recommended officially: Use two independent sessions to play the roles of "Writer" and "Reviewer."

Two sessions have independent contexts; the Reviewer isn't influenced by the Writer's logic and can find blind spots.

text
1Session A (Writer): "Implement API rate-limiting middleware"
2Session B (Reviewer): "Review the rate-limiting implementation in @src/middleware/rateLimiter.ts,
3 focusing on edge cases, race conditions, and consistency"
4Session A: "Fix review feedback: [Paste B's output]"

14. What NOT to do with Claude Code

Having said so much about "what to do," let's talk about "what not to do."

1. Don't let it do things you don't understand at all

If you know nothing about Kubernetes, don't let Claude Code write deployment configs for you to use directly. You cannot review what you don't understand.

2. Don't use it in environments without version control

No Git means no ability to roll back. Claude Code's changes might overwrite your files; using it without version control is like walking a tightrope without a net.

3. Don't throw a massive task at it all at once

"Migrate the whole project from JavaScript to TypeScript"

This instruction gives Claude Code free rein, making the result uncontrollable. Break it into small steps and confirm each step before moving to the next.

4. Don't expect perfection on the first try

Iteration is normal. Use /rewind to go back and use precise feedback to describe "what's wrong."

Summary

The core philosophy of using Claude Code is simple:

It is an extremely capable collaborator, but not an autopilot. The steering wheel is always in your hands.

Ranked by importance, my advice is:

  1. Write CLAUDE.md well — Invest once, benefit in every conversation
  2. Give precise instructions — Goal + Constraints + Validation standards
  3. Use Plan Mode — Plan first, act later for complex tasks
  4. Manage context — /clear, /compact, Sub-agents
  5. Control permissions — Deny dangerous operations, allow common commands
  6. Commit frequently — Retain the ability to roll back

Do these, and Claude Code can multiply your efficiency several times over. Fail to do them, and it will only help you create chaos faster.

The value of a tool always depends on the person using it.

The above is a combination of Claude Code official documentation and practical experience. If you have better practices, feel free to share.

One-click save

Use YouMind for AI deep reading of viral articles

Save the source, ask focused questions, summarize the argument, and turn a viral article into reusable notes in one AI workspace.

Explore YouMind
For creators

Turn your Markdown into a clean 𝕏 article

When you publish your own long-form writing, images, tables, and code blocks make 𝕏 formatting painful. YouMind turns a full Markdown draft into a clean, ready-to-post 𝕏 article.

Try Markdown to 𝕏

More patterns to decode

Recent viral articles

Explore more viral articles