Best Practices

Best practices for efficient Claude Code usage, a comprehensive guide from project initialization to team collaboration

Best Practices

This document compiles experiences from Claude Code users in real-world development. Whether you're a newcomer just starting out with Claude Code or a seasoned user looking to boost efficiency, you'll find valuable tips here.

We organize content from beginner to advanced, so we recommend reading through once first, then gradually applying in your daily work.

Project Initialization Best Practices

A good start is half the battle. Before using Claude Code in a project for the first time, spend 10 minutes on initialization, and every subsequent interaction will be more efficient.

Step 1: Create CLAUDE.md

This is the most important step. CLAUDE.md serves as the project manual you write for Claude. When Claude Code starts up, it automatically reads this file to understand your project context.

Why is this step so important?

Without CLAUDE.md, you'll repeatedly explain the same things to Claude:

You: Install dependencies with pnpm
Claude: Okay, running npm install...
You: Not npm, pnpm!
Claude: Sorry, running pnpm install...

With CLAUDE.md, these basics only need to be said once.

CLAUDE.md Template Example:

# My Project Name

## Overview
This is an e-commerce backend management system based on Next.js 15, written in TypeScript.

## Tech Stack

- Runtime: Node.js 22 LTS
- Framework: Next.js 15 (App Router)
- Styling: Tailwind CSS v4
- Database: PostgreSQL 16 + Prisma ORM
- Package Manager: pnpm 9
- Testing Framework: Vitest + Playwright

## Common Commands

- Install dependencies: `pnpm install`
- Development server: `pnpm dev` (port 3000)
- Run tests: `pnpm test`
- Lint code: `pnpm lint`
- Database migration: `pnpm prisma migrate dev`
- Production build: `pnpm build`

## Coding Standards

- Strictly use TypeScript, no `any` allowed
- React components use functional style with hooks
- Styles only use Tailwind, no inline styles or CSS files
- All API routes return `{ success: boolean, data?: T, error?: string }`
- Database queries go through the service layer, don't call Prisma directly in routes
- Commit message format: `feat:` / `fix:` / `docs:` / `refactor:` prefixes

## Project Structure

- `src/app/` โ€” Pages and API routes (App Router)
- `src/components/` โ€” Reusable UI components
- `src/components/ui/` โ€” Base components (Button, Input, etc.)
- `src/services/` โ€” Business logic layer
- `src/lib/` โ€” Utility functions and configuration
- `prisma/` โ€” Database schema and migration files

## Notes

- Don't manually modify files under `prisma/migrations/`
- Environment variables are in `.env.local` (not committed to Git)
- API authentication middleware is in `src/middleware.ts`
- Image assets go in `public/images/`, use next/image component for loading

Use /init for Quick Generation:

If you don't want to write manually, use the /init command to have Claude automatically analyze your project and generate one:

/init

Claude will scan your project structure, package.json, configuration files, etc., and automatically generate a CLAUDE.md. Then you can manually add any team conventions it might have missed.

Step 2: Configure .claudeignore

Similar to .gitignore, .claudeignore tells Claude which files don't need attention. This not only speeds up searching but also prevents Claude from being distracted by irrelevant files.

# .claudeignore

# Dependency directories
node_modules/
vendor/
.venv/

# Build outputs
dist/
build/
.next/
out/

# Large data files
*.sql
*.csv
*.sqlite
data/

# Binary and media files
*.jpg
*.png
*.mp4
*.zip

# Auto-generated code
generated/
*.gen.ts
prisma/migrations/

# Logs
logs/
*.log

Step 3: Describe Directory Structure in CLAUDE.md

This step is often overlooked but quite effective. Once Claude understands your directory structure, it knows where to find files and where to create new ones:

## Project Structure
src/
โ”œโ”€โ”€ app/                 # Next.js App Router
โ”‚   โ”œโ”€โ”€ (auth)/          # Pages requiring authentication
โ”‚   โ”œโ”€โ”€ (public)/        # Public pages
โ”‚   โ””โ”€โ”€ api/             # API routes
โ”œโ”€โ”€ components/
โ”‚   โ”œโ”€โ”€ ui/              # Base UI components (shadcn/ui)
โ”‚   โ”œโ”€โ”€ forms/           # Form components
โ”‚   โ””โ”€โ”€ layouts/         # Layout components
โ”œโ”€โ”€ services/            # Business logic (one file per module)
โ”œโ”€โ”€ hooks/               # Custom React hooks
โ”œโ”€โ”€ lib/                 # Utility functions
โ”‚   โ”œโ”€โ”€ auth.ts          # Authentication related
โ”‚   โ”œโ”€โ”€ db.ts            # Database connection
โ”‚   โ””โ”€โ”€ validators.ts    # Zod schema definitions
โ””โ”€โ”€ types/               # TypeScript type definitions

Daily Coding Best Practices

After initialization, these daily habits will help you work more efficiently.

Describe Requirements Clearly, Not Vague Instructions

This is the most basic and important principle. Claude is not a mind readerโ€”the clearer you are, the better it performs.

Vague instructions (ineffective) Clear descriptions (effective)
"Fix the login feature" "Add login failure rate limiting in src/app/api/auth/login/route.ts: lock for 15 minutes after 5 failures from the same IP within 5 minutes, use Redis to store the count"
"Help me write a component" "Create a UserAvatar component in src/components/ui/. It should accept two props: name and imageUrl. Show name initials when no image is provided. Use Tailwind's rounded-full for circular avatars"
"There's a bug, fix it" "Users report that filter conditions are lost after clicking pagination on the product list page. Please check the pagination logic in src/app/products/page.tsx to ensure URL query params are preserved during pagination"

Use @ References to Provide Context

When you need Claude to reference specific files, use the @ symbol for direct referencesโ€”it's faster and more accurate than letting it search:

Look at @src/services/order-service.ts and @src/types/order.ts,
then add a cancel order method to order-service, checking if the order status allows cancellation.

Several @ Reference Methods:

@src/services/auth.ts       # Reference a single file
@src/components/            # Reference an entire directory
@package.json               # Reference a config file
@https://nextjs.org/docs    # Reference online docs (will fetch content)

Cost-saving tip: Actively use @ to reference relevant files instead of letting Claude search the entire project. When Claude searches, it reads many files, consuming extra tokens.

Do One Thing at a Time

Avoid cramming too many tasks into one prompt. Claude performs best when focused on one thing:

# Not recommended: asking for too much at once
"Add avatar upload to the user module,๏ผŒ้กบไพฟๆŠŠ็™ปๅฝ•้กต็š„ๆ ทๅผๆ”นไธ€ไธ‹๏ผŒ
่ฟ˜ๆœ‰้‚ฃไธชๆœ็ดขๆก†็š„้˜ฒๆŠ–ไนŸๅŠ ไธŠ๏ผŒๅฏนไบ†ๅฏ†็ ้‡็ฝฎ็š„้‚ฎไปถๆจกๆฟไนŸๆ›ดๆ–ฐไธ€ไธ‹ใ€‚"

# Recommended: do it step by step
Step 1: "Add avatar upload to UserProfile component, use S3 for storage"
Step 2: "Update login page styles, refer to @docs/design-spec.md for the design"
Step 3: "Add 300ms debounce to the search box using a custom hook"
Step 4: "Update password reset email template, match the style of @src/templates/welcome.html"

Have Claude Read Before Modifying

When working with existing code, having Claude understand the code first before making changes is far more effective than jumping straight to modifications:

# Step 1: Understand first
"Read @src/services/payment-service.ts and explain the current payment flow processing logic,
especially error handling and retry mechanisms. Don't modify any code."

# Step 2: Plan next
"Based on your understanding, I want to add WeChat Pay as a payment channel.
Please create a modification plan, listing what needs to be changed."

# Step 3: Execute modifications
"The plan looks good, let's start. Modify payment-service.ts first."

Use Plan Mode for Complex Tasks

For large tasks involving multiple files, use Plan Mode (press Shift+Tab to switch) to have Claude create a plan first:

[Plan Mode]
I need to add an RBAC (Role-Based Access Control) permission system to the existing system.
Currently users only have admin and user roles. I need to support custom roles and fine-grained permissions.
Please analyze the existing code first and create a detailed implementation plan.

Claude will generate a step-by-step plan. After you confirm, switch back to normal mode and execute step by step.

Use /clear and /compact Wisely

These two commands are essential context management tools:

/compact    # Compress current conversation history, keeping key information, freeing up context space
/clear      # Completely clear conversation history, start fresh

# When to use:
# - Switching to a completely different task โ†’ /clear
# - Same task but conversation is too long โ†’ /compact
# - Feeling Claude's responses are getting worse (context overload) โ†’ /compact
# - Just finished one feature, starting the next โ†’ /clear

Important principle: When you switch topics, definitely /clear first. Leftover old context wastes tokens and may interfere with Claude's responses.

Code Review Best Practices

Claude Code can not only write code but also help you review it.

Use the /review Command

Quickly review current Git changes:

/review

Claude will check all uncommitted changes and point out potential issues:

  • Logic errors and edge cases
  • Security concerns (SQL injection, XSS, etc.)
  • Performance problems
  • Inconsistent code style
  • Missing error handling

Have Claude Write Tests to Verify Changes

After modifying code, have Claude write tests to verify:

I just modified the cancel order logic in @src/services/order-service.ts.
Please write unit tests for this method, covering the following scenarios:
1. Normal cancellation of an unshipped order
2. Attempt to cancel a shipped order (should fail)
3. Cancel a non-existent order
4. Concurrent cancellation of the same order

Multi-Round Review Workflow

For important code changes, you can conduct multi-round reviews:

# Round 1: Overall review
"Review the latest changes to @src/services/payment-service.ts,
focusing on security and error handling."

# After making changes based on feedback, round 2:
"Please review the modified code again, this time focusing on performance and edge cases."

# Round 3 (optional): Comparison review
"Compare the code before and after changes to confirm all issues are fixed and no new problems were introduced."

Debugging Best Practices

Bug fixing is one of Claude Code's strengths. Mastering the right debugging approach helps Claude locate issues faster.

Provide Complete Error Logs

Don't just show Claude the last line of the error messageโ€”provide the full context:

Got an error when running pnpm build, full error log below:

Type error: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

42 | const user = await getUser(session.userId) | ^^^^^^^ 43 | return NextResponse.json(user)

This error occurs in @src/app/api/user/route.ts.
I suspect it's a session type definition issue, please check.

Debug Step by Step: Diagnose First, Then Fix

Don't rush to have Claude fix directlyโ€”have it diagnose first:

# Step 1: Diagnose
"Users report that they occasionally get redirected to a 404 page after logging in.
Please check @src/middleware.ts and @src/app/(auth)/layout.tsx,
and analyze what might be causing this issue. Don't modify code yet."

# Step 2: Confirm the cause, then fix
"Your analysis makes senseโ€”it's indeed a redirect logic issue when the session expires.
Please fix this issue and add appropriate error logging to help with future troubleshooting."

Use Screenshots to Help

Claude Code supports reading screenshots, which is especially useful for UI-related bugs:

Look at this screenshot @screenshot.pngโ€”the last column text in the table is being cut off.
Please check the styles in @src/components/DataTable.tsx and fix this issue.

In the terminal, you can directly drag and drop an image into Claude Code's input area and it will process automatically.

Git Workflow Best Practices

Claude Code is deeply integrated with Git. Leveraging these features makes version management easier.

Use /commit to Auto-Generate Commit Messages

Claude will analyze your code changes and automatically generate standardized commit messages:

/commit

Generated commit messages typically include:

  • Change type prefix (feat, fix, refactor, etc.)
  • Concise change description
  • Affected scope

If you're not satisfied with the auto-generated message, you can request changes:

/commit
# Claude's generated message not good enough?
"Please make the commit message more detailed, explaining why this logic was changed"

Feature Branches + PR Workflow

Recommended workflow:

# 1. Create feature branch
git checkout -b feature/order-cancel

# 2. Start Claude Code development
claude

# 3. Multiple small commits during development
> "Implement basic order cancellation logic"
> /commit

> "Add cancel reason field and validation"
> /commit

> "Add unit tests for order cancellation"
> /commit

# 4. Finish development, create PR
> Create a Pull Request for the current branch, summarize all commit changes, generate a standardized PR description

Avoid Direct Modifications on Main Branch

# Add this rule in CLAUDE.md:
## Git Standards

- All modifications must be done on feature branches, don't modify main branch directly
- Branch naming: feature/xxx, fix/xxx, refactor/xxx
- Run `pnpm lint && pnpm test` before committing to ensure everything is fine

After writing this in CLAUDE.md, Claude will automatically follow these rules. If you accidentally ask Claude to modify code on main branch, it will remind you to create a branch first.

Team Collaboration Best Practices

When using Claude Code in a team, unified standards make collaboration smoother.

Share CLAUDE.md Standards

Commit CLAUDE.md to the Git repository so team members share the same project configuration:

# CLAUDE.md in project root โ†’ commit to Git
git add CLAUDE.md
git commit -m "docs: add CLAUDE.md project configuration"

# Personal preference configs โ†’ put in .claude/CLAUDE.md, add to .gitignore
echo ".claude/CLAUDE.md" >> .gitignore

Team CLAUDE.md should include:

  • Project tech stack and architecture explanation
  • Coding standards and naming conventions
  • Common commands and scripts
  • Directory structure explanation
  • Team agreements (branch strategy, commit standards, review process)

Personal .claude/CLAUDE.md can include:

  • Personal coding preferences
  • Common code snippets
  • Specific development environment configuration

Standardize PR Review

Define PR review standards in CLAUDE.md so Claude performs consistent reviews:

## PR Review Standards
When reviewing code, check the following aspects:
1. **Functional correctness**: Does it fully implement the requirements?
2. **Error handling**: Are edge cases covered?
3. **Security**: Any risks of SQL injection, XSS, permission bypass?
4. **Performance**: Any unnecessary database queries or memory leaks?
5. **Test coverage**: Do new code changes have corresponding tests?
6. **Code style**: Does it conform to project standards?
7. **Documentation**: Do public APIs have JSDoc comments?

Code Style Consistency

Enforce unified code style through CLAUDE.md:

## Code Style

- Naming: Components use PascalCase, functions/variables use camelCase, constants use UPPER_SNAKE_CASE
- File names: Component files use PascalCase (e.g., UserAvatar.tsx), others use kebab-case
- Import order: React โ†’ third-party libraries โ†’ internal modules โ†’ types โ†’ styles
- Maximum function length: 50 lines, split if exceeded
- Define interface when component props exceed 3

Advanced Tips Summary

Here are some advanced tips accumulated by experienced users:

Custom Slash Commands

Create custom command templates in the .claude/commands/ directory:

# .claude/commands/review-security.md
Please conduct a security review of the following code, focusing on:
1. SQL injection risks
2. XSS attack surface
3. CSRF protection
4. Completeness of permission checks
5. Whether sensitive data is encrypted
6. Whether sensitive information is leaked in logs

Review scope: $ARGUMENTS

When using:

/review-security @src/app/api/

Multi-File Coordinated Modifications

When you need to modify multiple files simultaneously, give Claude a clear overall view:

I need to add a coupon feature to the order system, involving the following files:

- @src/types/coupon.ts โ€” new, define coupon types
- @src/services/coupon-service.ts โ€” new, coupon business logic
- @src/services/order-service.ts โ€” modify, apply coupon during checkout
- @src/app/api/coupons/route.ts โ€” new, coupon API
- @prisma/schema.prisma โ€” modify, add Coupon model

Please handle them in the order above, and tell me after completing each file.

Leverage Extended Thinking

For complex architectural decisions, let Claude use extended thinking:

[Using Opus model]
I'm considering migrating the current REST API to GraphQL.
Please analyze the pros and cons in depth, considering the following factors:
1. Migration cost for existing 50+ API endpoints
2. Benefits of frontend query optimization
3. Changes in caching strategy
4. Team learning curve
5. Integration plan with existing React Query

No need to write code, give me a detailed technical analysis report.

Have Claude Verify Its Own Changes

Develop the habit of having Claude verify its own modifications:

After completing the modifications, please:
1. Run pnpm lint to check for formatting issues
2. Run pnpm test to confirm existing tests still pass
3. If there are type errors, fix them yourself

Common Pitfalls

Finally, here are some practices to avoid:

Pitfall Correct approach
Pasting entire file contents into the conversation Use @file path to reference
Asking Claude to do 5 things in one prompt Do one thing at a time, break it down
Being vague when describing requirements Provide specific files, behaviors, expected results
Not using CLAUDE.md Spend 10 minutes writing it, save countless hours later
Never using /clear or /compact /clear when changing topics, /compact when conversation is long
Having Claude modify without understanding first Read code first, then plan, then execute
Using Opus for everything Use Sonnet for daily tasks, Opus only for complex decisions
Repeatedly retrying the same command when it fails Try a different approach, provide more context

Mastering these best practices takes time. We recommend starting with the most fundamental points: create CLAUDE.md, describe requirements clearly, and do one thing at a time. These three points alone will significantly improve your experience. As you use it more deeply, gradually apply more advanced techniques.

๐Ÿš€
Get Started with QCode โ€” AI Coding Assistant
Official Claude Code relay, fast and reliable, ready to use
View Pricing Plans โ†’ Create Account