Claude Code Tips and Best Practices

Canonical version: Claude Code Tips and Best Practices.

General tips

  • Course correct early and often: cancel whatever Claude is doing and adapt your prompt whenever needed
  • Use claude --continue to continue your last conversation
  • Use /clear to keep the context "clean" (focused)
  • Use /add-dir <new dir> to work with multiple directories in a single session
  • Pipe data into Claude instead of copy/pasting (e.g., cat foo.txt | claude)
  • Ask Claude to read files or fetch URLs (also works with images!)
  • Enable sound alerts: claude config set --global preferredNotifChannel terminal_bell
  • Vim key bindings via /vim or /config: https://docs.anthropic.com/en/docs/claude-code/settings#vim-mode
  • Add/configure/leverage Model Context Protocol (MCP) servers
  • Run multiple tasks in parallel: Use 3 parallel agents to ...
  • Drag and drop images or copy/paste into Claude Code to analyze them
  • Use git, gh (GitHub CLI), and other CLI tools from within Claude Code
  • Prompt stashing: long prompt, short detour? Ctrl+S stashes your draft so you can fire off a quick question first. The stashed prompt restores automatically after you submit (tip from Ado: https://x.com/adocomplete/status/2029988814924722559)
  • Background bash commands: prompt Claude to run in background, or Ctrl+B to move a running command to background. Output is buffered and retrievable. Disable with CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1
    • Hit the down arrow in chat, select a background command, hit enter for details. Kill any with k
  • Launch background sessions programmatically: claude --bg --name "Session Name" "Prompt goes here" dispatches a new named session that runs in the background and shows up in the agent view (claude agents). Perfect for handing work off to a parallel session without opening a new terminal — the session is just... already running when you check on it
  • Use # to quickly add something to memory
  • Use ! <command> to run a shell command without leaving Claude Code. Adds command + output to context, supports Ctrl+B backgrounding, and has history-based Tab autocomplete. Exit with Escape, Backspace, or Ctrl+U on empty prompt
  • YOLO mode alias: alias cc="claude --dangerously-skip-permissions" (use with caution!)
  • Add IS_SANDBOX=1 claude --dangerously-skip-permissions for fully unrestricted mode
  • Use "Correct me if I'm wrong" to decrease AI Sycophancy
  • Front-load the most important instruction at the top of the prompt
  • Assume zero context: Claude knows nothing about your project. Tell it everything it needs
  • Run /init to generate a starter CLAUDE.md for your project
  • /rewind or double-tap ESC to open the checkpoint menu and roll back
  • /plugin to browse the plugin marketplace. Plugins add skills, tools, and integrations without config
  • For larger projects, have Claude interview you first: ask it to use AskUserQuestion to clarify requirements before starting
  • Ask Claude to score its output against pre-defined success criteria
  • Use other LLMs to plan and generate mega prompts before opening Claude Code (saves tokens from Plan Mode)

Context management

  • /context: visualize context usage and get optimization tips
  • /context all: per-item token counts for MCP tools, custom agents, memory files and skills. Run it in a fresh session to see your baseline startup cost before any conversation. Built-in tools stay a single "System tools" line
  • /compact [focus]: compress context with an optional focus instruction
  • Auto-compact triggers at ~95% capacity
  • Idle compaction (v2.1.299+, on by default): a 200K+ token conversation left idle for ~54 minutes gets compacted right before its 1h prompt cache expires, so coming back costs a summary instead of the full history. Keep it for long sessions you resume casually. For a deep session where nuance matters, run /compact focus on X yourself before you leave, or turn it off with "idleCompaction": false (raise the threshold with CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS if you only want it on huge sessions). Details: Claude Code Prompt Caching
  • CLAUDE.md content survives compaction
  • claude -c: continue the last conversation
  • claude -r "name": resume a named session
  • /btw question: side question with no context cost
  • --max-budget-usd 5: cap session cost
  • Pipe input for one-shot queries: cat file | claude -p "Summarize"
  • Don't context-switch mid-session. /clear between unrelated tasks; mixing topics pollutes context with irrelevant information
  • Scope investigations narrowly or use subagents so open-ended exploration doesn't fill main context
  • After two failed corrections, /clear and write a better initial prompt incorporating what you learned rather than adding more corrections

Skill hygiene: the listing tax

Every installed skill adds its name and description to context on every turn, used or not. Two hundred skills is a silent tax you pay on every message. Addy Osmani's comparison: JavaScript bundle bloat, which nobody notices until someone measures it per item. The routine, once a month or after any big skill import:

  1. /skill-doctor: context cost and invocation count per skill
  2. /skills: disable the dead ones (check first that "never invoked" isn't "invoked once a quarter, critically")
  3. /context: confirm the listing size the model actually receives after the budget is applied
  4. /usage: session and weekly consumption against plan limits
  5. /doctor (alias /checkup): version, auth, PATH, file debt

Then /claude-api prompt-audit on your most-used skills. Verification rituals, emphasis boosters, and stale few-shot examples were needed two model generations ago. Now they cost tokens and fight the model. See Claude Code Skills and, to measure whether a skill changes outcomes at all, Claude Code Plugin Evals.

Session management with 1M context

With the 1M token context window, Claude Code can operate autonomously for longer — but only if you manage sessions well. Context rot (the gradual drop in model quality as the window fills) makes active session management more important, not less.

Every turn is a branching point. After Claude finishes a turn, you have five choices:

  1. Continue — send another message in the same session
  2. /rewind (or double-tap Esc) — jump back to a previous message and retry from there
  3. /clear — start a new session, usually with a brief you've distilled from what you just learned
  4. Compact — summarize the session so far and keep going on top of the summary
  5. Subagents — delegate the next chunk of work to a subagent with its own clean context, and only pull its result back

Rules of thumb:

  • New task → new session. Related follow-ups (e.g., writing docs for a feature you just shipped) can stay in the same session to reuse context
  • Rewind beats correcting. If Claude went down a bad path, /rewind is cleaner than piling on corrections — the failed attempt stays in context and poisons future reasoning
  • Use "summarize from here" at a good state to produce a handoff brief for /clear or a fresh session
  • /clear with a hand-written brief is often better than /compact for a genuinely new chunk of work. Compact preserves detail but inherits whatever context rot was already present
  • Bad compacts happen when autocompact fires mid-debugging and drops information that mattered for a later turn. Because context rot is at its worst right before compaction, the summary is produced by the model at its least intelligent point — compact deliberately, not reactively

Subagent mental test: "Will I need this tool output again, or just the conclusion?" If only the conclusion, spawn a subagent so the raw exploration stays out of your main context. Explicit triggers:

  • "Spin up a subagent to verify this work against the spec file"
  • "Spin off a subagent to read through codebase X and summarize how it implemented auth"
  • "Spin off a subagent to write the docs on this feature based on my git changes"

Reference: https://x.com/trq212/status/2044548257058328723 (Thariq, Claude Code team)

Handoff documents instead of compaction

/compact summarises at the point where the session is least sharp. A cleaner pattern for long work: before the context fills, ask Claude to write a handoff file, then start fresh from it.

Put the rest of the plan in <folder>/HANDOFF.md. Explain what you tried, what worked, what didn't, so that the next agent with fresh context can load that file and nothing else to finish the task.

Review it (one or two "did you include X?" follow-ups), /clear, then paste only the path as the first message of the new session. In later sessions, ask the agent to update the same file for the next one. If you want full control over when compaction happens, turn auto-compact off in /config (or move the trigger earlier with /autocompact). That also turns off idle compaction; to keep auto-compact and stop only the idle one, set "idleCompaction": false (see Claude Code Configuration). Related: the deterministic alternative is cloning a conversation and keeping only the later half of the messages; /branch and claude -c --fork-session give you native forks from any point.

Getting things in and out

  • In: when a URL won't fetch (paywall, login, Reddit), select all on the page, copy, paste into the prompt. Gmail threads: use "Print all" for an expanded view first. YouTube: "Show transcript", then select all. Text with links from Slack loses them on paste; route it through a Markdown-aware editor first, or ask Claude to read the clipboard (pbpaste, wl-paste)
  • Out: /copy puts the last response on the clipboard as Markdown. Or have Claude write to a file and open it in your editor at a specific line, or open a URL in your browser, or open the repo in a GUI git client. For a PR description, let it edit a local file, check it, then push the text back with gh
  • Paths: realpath some/relative/path when you need to hand a file in another folder to a session
  • Big prompts: Ctrl+G opens the prompt in $EDITOR (set it in your shell or under env in settings.json); pasting long text there is faster than into the terminal

Verification habits

  • Close the write-test loop for anything autonomous. git bisect, a flaky CI job, a refactor: Claude only works unattended when it can check its own result. For interactive programs (including Claude Code itself), drive them through tmux: new-session -d, send-keys, sleep, capture-pane -p, assert on the output
  • Browser checks: Playwright MCP (accessibility tree, cheaper, more reliable) for most web verification; the native Chrome integration when you need a logged-in profile or coordinate clicks. If you use the latter, tell it in CLAUDE.md to use read_page and find refs instead of coordinates and to never screenshot unless asked
  • "Double check every single claim in what you produced and end with a table of what you could verify." Works on research output as well as code
  • TESTING.md: for a large review (a teammate's PR, a big Claude-generated change), have Claude test everything, document how each part was verified in a TESTING.md, and review that document instead of the diff. Keep it in git as a running log
  • TDD, in this order: write the tests, watch them fail, commit them, then implement. The committed failing tests are the contract. Read the tests; a test that returns true is worse than none
  • Draft PRs by default. Let Claude open a draft, review it, then mark it ready. Allow git pull automatically, keep git push on manual approval

Long-running and parallel work

  • Manual exponential backoff for builds and CI: "check every 1, 2, 4, 8 minutes until it's done". Cheaper than gh run watch, which streams lines you pay for. Use gh run view <id> | grep <job> per check
  • Ctrl+B backgrounds a running command; subagents run in the background by default. Ask for the number of subagents, which model each should use (Haiku for grep-shaped work, Fable for judgement), and foreground or background
  • Terminal tabs as a cascade: one tab per task, new tasks open to the right, sweep left to right. Three or four tasks at a time is the ceiling before quality drops, whatever the tooling
  • Worker in a container: your local session starts a tmux session, launches a containerised Claude Code with --dangerously-skip-permissions inside it, and drives it with send-keys / capture-pane. Fully autonomous, sandboxed, results pulled back when done. Same trick works for orchestrating Codex or other CLIs
  • Remote Control from your phone: /rc inside a session, or claude remote-control --spawn=worktree --capacity=N to start fresh sessions remotely, each in its own worktree. Turn it off when not in use (a session is a shell on your machine); remoteControlAtStartup: true in settings if you want it always on

Settings worth setting

{
  "attribution": { "commit": "", "pr": "", "sessionUrl": false },
  "permissions": { "defaultMode": "auto", "allow": ["Read(~/.claude)", "Read(//tmp/**)"] },
  "outputStyle": "Concise",
  "promptSuggestionEnabled": false,
  "env": { "EDITOR": "nvim" }
}
  • attribution removes the Co-Authored-By trailer and the PR footer (replaces the deprecated includeCoAuthoredBy); sessionUrl: false drops the Claude-Session: trailer
  • outputStyle: Concise (v2.1.237+) makes Claude lead with the result. It changes the visible text only, not the thinking
  • Shell aliases pay off fast: c=claude, ch='claude --chrome', cr='claude remote-control'; a small shell function can expand --fs to --fork-session
  • Ask Claude Code about Claude Code. It has a dedicated subagent for its own features; /release-notes shows what changed in your version

Git worktrees

Leverage worktrees to run multiple Claude instances in parallel:

  • claude -w feature-a: start Claude in an isolated worktree
  • git worktree add ../project-feature-a feature-a && cd ../project-feature-a && claude
  • Keep one terminal tab per worktree
  • Use separate IDE windows for different worktrees
  • Cleanup: git worktree remove ../project-feature-a
  • isolation: worktree in agent frontmatter runs a subagent in its own worktree
  • sparsePaths in worktree config to checkout only needed directories
  • /batch auto-creates worktrees for parallel changes

Useful prompt to let Claude handle worktrees:

I want to run Claude Code in multiple terminal windows on this codebase simultaneously.
The recommended way is using git worktrees. Ultrathink about this and plan, then create
a set of rules in a new "worktrees" folder with a Markdown file for each of the following:
init, create, merge, pr for, sync, remove a worktree. Consider conflicting issues like ports.

Reference: https://x.com/iannuttall/status/1938177015384805548

Extended thinking and effort

Since Opus 4.6 (Feb 2026), Claude Code uses adaptive thinking by default: the model decides how long to think, which tends to outperform fixed thinking budgets across the board. Opt out with CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1

Since Mar 2026, the default reasoning effort is medium (85), a sweet spot on the intelligence-latency-cost curve for most users. To increase intelligence at the cost of more tokens and latency:

  • /effort high — sticky across sessions, shareable via settings.json
  • /effort max — even higher effort for the rest of the conversation
  • ULTRATHINK keyword in a prompt — max effort for a single turn only

Anthropic plans to default Teams and Enterprise users to high effort

Counterintuitive since Claude Fable 5.1: the bigger model at low effort often beats the smaller model at high effort, on both score and cost per task. On CursorBench 3.2.0, Fable 5.1 at low effort matches Fable 5 at high effort at a third of the cost (Lance Martin, Anthropic). Try /model fable + /effort low before reaching for Opus at xhigh. Effort can now change mid-conversation without invalidating the prompt cache, so plan at high and implement at low inside one session. /effort saves a separate level per model; s applies to the session only. maxEffortLevel in settings caps effort on every provider.

Thinking keywords (escalating depth):

  • think — basic extended thinking
  • think hard — deeper
  • ultrathink — deepest (equivalent to max effort for that turn)

Model switching

In the /model picker, Enter changes your default. Press s to change the session only.

Easy to get wrong, and the cost is silent: you dip into a more expensive model for one conversation that warrants it, hit Enter, and every later session keeps using it until you notice. That's the whole tip, via Craigory Coppola.

The useful habit that follows: treat s as the default gesture and Enter as a deliberate decision about how you want to work from now on. Same distinction as /effort high being sticky across sessions versus ULTRATHINK applying to a single turn. Claude Code repeatedly offers per-turn, per-session and persistent versions of the same control, and knowing which one you just pulled is most of the skill.

Prompt structure

XML-like tags help Claude isolate different parts of long prompts:

<instructions>Foo</instructions>
<requirements>Bar</requirements>
<rules>Baz</rules>

A practical prompting structure: [Role] + [Task] + [Context]

Recommendations

  • Avoid pasting long content. Use file-based workflows instead
  • Create CLAUDE.md files to customize behavior (see Claude Code Memory)
  • Explore > Plan > Confirm > Do: Analyze X then propose different approaches and let me choose one before you continue
  • Leverage screenshots: Do X then screenshot Y using Z and ...
  • Leverage commands to automate specific tasks
  • Give Claude a way to verify its work: include tests, screenshots, or expected outputs so Claude can self-check. Highest-leverage tip
  • Create skills from great outputs: paste a good result and ask Claude to turn it into a reusable skill. Also works with screenshots
  • Version skills: duplicate and version as you refine instead of editing live ones
  • Define custom subagents in .claude/agents/ for isolated, specialized tasks
  • If CLAUDE.md gets too long, Claude ignores half of it. Prune ruthlessly; delete rules Claude already follows by default, or convert mandatory behaviors to hooks

More: https://www.anthropic.com/engineering/claude-code-best-practices

Debugging and error handling

  • Re-run only the broken step instead of regenerating everything
  • Ask Claude to intentionally reproduce a failure to understand it
  • Revert to the last known good prompt and reapply changes one at a time
  • Have Claude walk through how it generated an answer step by step

Status line

Claude Code supports custom status lines via statusLine in ~/.claude/settings.json. See Claude Epic Status Line for a feature-rich implementation with colors, rate limits, git info, session cost, worktree detection, and auto-compact warnings.

Plugins

Conversation history on disk

Every session is a .jsonl under ~/.claude/projects/<path-with-slashes-as-dashes>/. That makes history greppable:

grep -l -i "keyword" ~/.claude/projects/-home-you-wks-*/*.jsonl
find ~/.claude/projects/*/*.jsonl -mtime 0 -exec grep -l -i "keyword" {} \;
jq -r 'select(.type=="user") | .message.content' ~/.claude/projects/.../<id>.jsonl

Or ask: "what did we discuss about X yesterday?" and let Claude search its own transcripts. This is also what osk-meta-session-harvest mines.

Utilities

Templates

References


About Sébastien

Ready to get to the next level?

Found this valuable? Share it with someone who needs it.

Join 6,000+ readers. Get practical systems for knowledge & AI. Free.

Subscribe ✨

Free: Knowledge System Checklist

A clear roadmap to building your own knowledge system. Subscribe and get it straight to your inbox.

6,000+ readers. No spam. Unsubscribe anytime.

Subscribe