Practice
Comments in React / JSX are similar to JavaScript multi-line comments, but wrapped in curly braces.
Single-line comments:
{ // single-line comments (in vanilla JavaScript, single-line comments are written with a double slash (//))
}
Multi-line comments:
{ / * Multi-line comment spanning more than
one line * /}
Writing comments in React code is useful for several reasons:
Documentation: comments can serve as a form of documentation for your code. They help other developers, or even you yourself, understand what a particular piece of code does and what decisions were made.
Explaining complex decisions: if you have a complex algorithm, solution or some non-trivial data manipulation, comments can help explain how it works and why it is implemented that way.
Warnings and notes: sometimes the code contains temporary workarounds, non-obvious solutions or places that need further work. Comments can be used to highlight such spots and warn other developers.
Help with debugging: comments can help when debugging code by indicating what is expected in certain places or what to check when errors occur.
Commands and tasks: in comments you can leave notes for yourself or for other team members, indicating what needs to be done in the future or which tasks remain unfinished.
Examples of using comments in React:
// A simple comment explaining the purpose of the component
function MyComponent() {
// TODO: Add error handling
// FIXME: This code needs optimisation
// NOTE: Important information about how this function works
return <div>Hello, world!</div>;
}
// A comment describing the component's props
function AnotherComponent({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
// A comment describing complex logic inside a functional component
function ComplexComponent() {
// Complex logic for displaying the data is performed here
return <div>Some complex UI here...</div>;
}
It is important to remember that well-written comments make code more readable and maintainable, but avoid excessive commenting or comments that restate the obvious, such as "this code sets the value of a variable".
Comments