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 --continueto continue your last conversation - Use
/clearto 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
/vimor/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+Sstashes 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+Bto move a running command to background. Output is buffered and retrievable. Disable withCLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1- Hit the down arrow in chat, select a background command, hit enter for details. Kill any with
k
- Hit the down arrow in chat, select a background command, hit enter for details. Kill any with
- 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, supportsCtrl+Bbackgrounding, and has history-based Tab autocomplete. Exit withEscape,Backspace, orCtrl+Uon empty prompt - YOLO mode alias:
alias cc="claude --dangerously-skip-permissions"(use with caution!) - Add
IS_SANDBOX=1 claude --dangerously-skip-permissionsfor 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
/initto generate a starter CLAUDE.md for your project /rewindor double-tapESCto open the checkpoint menu and roll back/pluginto 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 Xyourself before you leave, or turn it off with"idleCompaction": false(raise the threshold withCLAUDE_CODE_IDLE_COMPACT_MIN_TOKENSif you only want it on huge sessions). Details: Claude Code Prompt Caching - CLAUDE.md content survives compaction
claude -c: continue the last conversationclaude -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.
/clearbetween 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,
/clearand 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:
/skill-doctor: context cost and invocation count per skill/skills: disable the dead ones (check first that "never invoked" isn't "invoked once a quarter, critically")/context: confirm the listing size the model actually receives after the budget is applied/usage: session and weekly consumption against plan limits/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:
- Continue — send another message in the same session
/rewind(or double-tapEsc) — jump back to a previous message and retry from there/clear— start a new session, usually with a brief you've distilled from what you just learned- Compact — summarize the session so far and keep going on top of the summary
- 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,
/rewindis 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/clearor a fresh session /clearwith a hand-written brief is often better than/compactfor 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:
/copyputs 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 withgh - Paths:
realpath some/relative/pathwhen you need to hand a file in another folder to a session - Big prompts:
Ctrl+Gopens the prompt in$EDITOR(set it in your shell or underenvinsettings.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 throughtmux: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.mdto useread_pageandfindrefs 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
trueis worse than none - Draft PRs by default. Let Claude open a draft, review it, then mark it ready. Allow
git pullautomatically, keepgit pushon 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. Usegh run view <id> | grep <job>per check Ctrl+Bbackgrounds 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
tmuxsession, launches a containerised Claude Code with--dangerously-skip-permissionsinside it, and drives it withsend-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:
/rcinside a session, orclaude remote-control --spawn=worktree --capacity=Nto 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: truein 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" }
}
attributionremoves theCo-Authored-Bytrailer and the PR footer (replaces the deprecatedincludeCoAuthoredBy);sessionUrl: falsedrops theClaude-Session:traileroutputStyle: 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--fsto--fork-session - Ask Claude Code about Claude Code. It has a dedicated subagent for its own features;
/release-notesshows 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 worktreegit 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: worktreein agent frontmatter runs a subagent in its own worktreesparsePathsin worktree config to checkout only needed directories/batchauto-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 conversationULTRATHINKkeyword 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 thinkingthink hard— deeperultrathink— 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.mdfiles 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
- Codex plugin for Claude Code — integrate OpenAI Codex for code review and task delegation (
/codex:review,/codex:rescue)
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
- Claude Account Switcher — one isolated config + credential store per account (
claude account add/use/list), so work and personal stop fighting over the same login. The DIY version isCLAUDE_CONFIG_DIRplus a shell alias, orclaude setup-tokenper account and a shell function that setsCLAUDE_CODE_OAUTH_TOKENfrom the keyring before callingclaude. - ccusage — track real usage and costs (
npm install -g ccusage,npx ccusage blocks --live) - Trace Claude Code calls: https://github.com/badlogic/lemmy/tree/main/apps/claude-trace
- Explanations: https://simonwillison.net/2025/Jun/2/claude-trace
- https://github.com/possibilities/claude-composer
- Collection of resources: https://github.com/affaan-m/everything-claude-code
Templates
References
- Thariq on session management & 1M context: https://x.com/trq212/status/2044548257058328723
- Lydia Hallie on idle compaction (2026-10-14): https://x.com/lydiahallie/status/2110484840256819380 and https://x.com/lydiahallie/status/2110484841926152622
- Settings reference,
idleCompaction: https://code.claude.com/docs/en/settings-reference#idlecompaction - Context window docs (what survives compaction,
/compactwith a focus): https://code.claude.com/docs/en/context-window - Addy Osmani on
/skill-doctor,/skills,/doctor,/context,/usage: https://www.linkedin.com/posts/addyosmani_ai-programming-softwareengineering-share-7505321554847686656-X_2D - Lance Martin's Fable 5.1 tips (low effort, cache, prompt simplification): https://x.com/RLanceMartin/status/2094854835854295296
- Boris Cherny's hidden features thread: https://x.com/bcherny/status/2038454336355999749
- Best practices: https://www.anthropic.com/engineering/claude-code-best-practices
- Troubleshooting: https://docs.anthropic.com/en/docs/claude-code/troubleshooting
- Third-party integrations: https://docs.anthropic.com/en/docs/claude-code/third-party-integrations
- Proxy to connect to other LLMs: https://github.com/1rgs/claude-code-proxy
- History of system prompts: https://github.com/badlogic/cchistory
- How to extend Claude Code: https://code.claude.com/docs/en/features-overview
- Token usage tips: https://code.claude.com/docs/en/costs#reduce-token-usage
- Claude Superpowers (GitHub): https://github.com/obra/superpowers
- Claude Code course (inside Claude Code): https://ccforeveryone.com
Related
- Claude Code
- Claude Code Memory
- Claude Code Prompt Caching
- Claude Code Configuration
- Claude Code Skills
- Claude Code Plugin Evals
- Claude Fable 5.1
- Addy Osmani
- Claude Epic Status Line
- ccusage
- Claude Account Switcher
- Skills.sh
About Sébastien
Ready to get to the next level?
Found this valuable? Share it with someone who needs it.