Skip to main content

JSX Comments and Common Patterns: A Complete Guide

Comments are essential for readable code, but JSX has a specific commenting syntax that differs from HTML. This guide explains how to correctly add comments inside and outside JSX markup, common mistakes to avoid, and professional commenting patterns.

Key Takeaways

  • JSX comments inside markup must use {/* comment */} syntax, not HTML comments or //
  • Standard JavaScript comments (//, /* */) work fine outside the return statement
  • HTML comments <!-- --> render as visible text instead of being hidden—never use them in JSX
  • Comments should explain why code exists, not what it does (assume code is readable)
  • Consistent commenting improves team collaboration and code maintenance

How to Write Comments in JSX

JSX is fundamentally JavaScript, not HTML. When you write JSX inside a return statement, you're creating a JavaScript expression. Standard HTML comments don't work because JSX would try to render them as DOM nodes, displaying them as text on the page.

The correct syntax for comments inside JSX markup is {/* ... */}. This tells React: "Treat the curly braces as a JavaScript expression, and evaluate it as a block comment." The comment will not appear in the rendered output.

function UserCard() {
return (
<div>
{/* This comment will be hidden in the final output */}
<h1>Welcome</h1>
</div>
);
}

Single-Line vs. Multi-Line JSX Comments

Both single-line and multi-line information can go inside the {/* ... */} syntax. Use single-line for brief notes, multi-line for detailed explanations:

function DataDashboard() {
return (
<div>
{/* Quick note: data updates every 5 seconds */}
<h1>Live Dashboard</h1>

{/*
The following section renders user activity.
Data is fetched from the analytics API.
Performance: 200ms cache on the server.
*/}
<section className="activity-log">
{/* Activity items render here */}
</section>
</div>
);
}

Comments Outside the Return Statement

Any code outside the return statement is standard JavaScript. Use traditional JavaScript comments there:

function ProcessPayment() {
// Initialize payment processor with API key
const processor = new PaymentProcessor(process.env.STRIPE_KEY);

/*
* Validate user input before calling the API.
* This prevents unnecessary network requests.
*/
const validateAmount = (amount) => amount > 0;

return (
<form>
{/* Form submission handler */}
<button>Pay Now</button>
</form>
);
}

Common Pitfalls and Solutions

Pitfall 1: Using HTML Comments

HTML comment syntax <!-- ... --> does not work in JSX. React treats it as literal text and renders it on the page:

// INCORRECT - This will appear as text in the browser
<div>
<!-- This shows up on the page as plain text! -->
<p>Content</p>
</div>

Always use {/* ... */} instead.

Pitfall 2: Using Single-Line JavaScript Comments Directly

The // syntax cannot appear directly inside JSX markup. React's parser will choke because // is not a complete expression:

// INCORRECT - Syntax error
<div>
// This is not valid JSX
<p>Content</p>
</div>

Pitfall 3: Forgetting the Curly Braces

Comments must be wrapped in curly braces to signal a JavaScript expression. Without them, React tries to parse them as text:

// INCORRECT - Missing braces
<div>
/* This is not a comment */
<p>Content</p>
</div>

// CORRECT
<div>
{/* This is a comment */}
<p>Content</p>
</div>

Pitfall 4: Stale Comments

Comments that don't match the code are worse than no comments. When you refactor code, update or delete related comments:

// BAD - Comment is now false
{/* User fetches data on mount */}
// Data now comes from props, not useEffect

// GOOD
{/* User data passed via props from parent */}
<UserCard user={user} />

Professional Commenting Patterns

Pattern 1: Explain Complex Logic

Comments should clarify why a decision was made, not what the code does:

function CartTotal({ items }) {
// WEAK comment (restates the code)
// Add up all prices
const total = items.reduce((sum, item) => sum + item.price, 0);

// STRONG comment (explains business logic)
// Discounts only apply if total exceeds $100 to avoid processing fees
const discountedTotal = total > 100 ? total * 0.9 : total;

return <div>{discountedTotal}</div>;
}

Pattern 2: Mark Temporary or Unsafe Code

Use comments to flag code that may need refactoring:

function ImageGallery({ images }) {
return (
<div>
{/* TODO: Replace with infinite scroll (currently page 1 only) */}
{images.slice(0, 10).map(img => (
<img key={img.id} src={img.url} alt={img.title} />
))}
</div>
);
}

Pattern 3: Document Non-Obvious Data Structures

Comment the shape of complex objects:

function UserProfile({ user }) {
// user object structure: { id, name, email, roles: ['admin', 'editor'], joinedAt: ISO8601 }

return (
<div>
<h1>{user.name}</h1>
{user.roles.includes('admin') && <span>Admin</span>}
</div>
);
}

Frequently Asked Questions

Can I use HTML comments in JSX?

No. HTML comments <!-- --> do not work in JSX because React will render them as visible text nodes. Always use {/* */} for comments inside markup. HTML comments are only valid in .html files and template files outside React components.

Do JSX comments appear in the final rendered HTML?

No. JSX comments are stripped out during the build process. They exist only in source code for developers to read. The browser never receives them.

What is the difference between {/* */} and {//comment}?

{/* */} is the standard, documented way to comment in JSX. The {// comment} pattern works in some cases (inside curly braces on a single expression line) but is less reliable and not idiomatic React. Always use {/* */}.

Should I comment every line of code?

No. Comments should explain why non-obvious code exists, not restate what obvious code does. Self-documenting code (clear variable names, modular functions) reduces the need for comments. Aim for 1 comment per 10–20 lines of meaningful code.

How do I document component props?

Use JSDoc or TypeScript prop types, not inline comments. For TypeScript:

interface UserCardProps {
/** User's unique identifier */
userId: string;
/** Whether to show admin controls */
isAdmin?: boolean;
}

function UserCard({ userId, isAdmin }: UserCardProps) { ... }

Further Reading