Tips and Strategies for Writing Clean and Maintainable JSX Code

Rowsan Ali - Nov 8 '23 - - Dev Community

Writing clean and maintainable code is crucial for long-term project success, especially when working with JSX in React applications. Below are some essential tips and strategies, accompanied by code examples, to help you write better JSX.
Follow me on X

1. Keep Components Small and Focused

Divide your application into small, manageable components that do one thing and do it well. This makes your code easier to understand and test.

// Good
function UserProfile({ user }) {
  return (
    <div>
      <UserAvatar user={user} />
      <UserInfo user={user} />
    </div>
  );
}

// Avoid
function UserProfile({ user }) {
  // A large component that handles rendering everything related to the user
}
Enter fullscreen mode Exit fullscreen mode

2. Use Descriptive Component Names

Choose clear and descriptive names for components to indicate what they do or represent.

// Good
function EmailInputField() {
  // ...
}

// Avoid
function InputField() {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

3. Destructure Props for Clarity

Destructure props in functional components to make it clear which properties the component expects and uses.

// Good
function Greeting({ name, message }) {
  return <h1>{`Hello, ${name}! ${message}`}</h1>;
}

// Avoid
function Greeting(props) {
  return <h1>{`Hello, ${props.name}! ${props.message}`}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

4. Keep JSX Readable with Proper Indentation

Just like HTML, properly indented JSX is crucial for readability. Use a consistent indentation style.

// Good
return (
  <div>
    <h1>Title</h1>
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  </div>
);

// Avoid
return <div><h1>Title</h1><ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul></div>;
Enter fullscreen mode Exit fullscreen mode

5. Abstract Conditional Logic

Move complex conditional logic outside of your JSX to keep the template clean.

// Good
function WelcomeBanner({ user }) {
  const isLoggedIn = user != null;
  return (
    <div>
      {isLoggedIn ? <LoggedInBanner user={user} /> : <LoggedOutBanner />}
    </div>
  );
}

// Avoid
function WelcomeBanner({ user }) {
  return (
    <div>
      {user != null ? <LoggedInBanner user={user} /> : <LoggedOutBanner />}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

6. Use Comments Wisely

Inline comments can clarify the purpose of complex parts of the template, but avoid over-commenting obvious things.

// Good
function ComplexComponent() {
  // Fetching data from the API and filtering for active users
  // ...

  return (
    // Render only if there are active users
    {activeUsers.length > 0 && (
      <UserList users={activeUsers} />
    )}
  );
}

// Avoid
// This is a div
// ...
Enter fullscreen mode Exit fullscreen mode

7. Avoid Inline Styles

Prefer external stylesheets or styled-components over inline styles for better separation of concerns and reusability.

// Good
import "./Button.css";

function Button({ label }) {
  return <button className="primary-button">{label}</button>;
}

// Avoid
function Button({ label }) {
  return <button style={{ backgroundColor: 'blue', color: 'white' }}>{label}</button>;
}
Enter fullscreen mode Exit fullscreen mode

8. Prop Types and Default Props

Use propTypes for type-checking and defaultProps to define default values for props.

import PropTypes from 'prop-types';

function UserProfile({ name, age }) {
  // ...
}

UserProfile.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
};

UserProfile.defaultProps = {
  age: 30,
};
Enter fullscreen mode Exit fullscreen mode

9. Functional Over Class Components

Whenever possible, use functional components with hooks. They are more concise and easier to test.

// Good
function App() {
  const [count, setCount] = useState(0);
  // ...
}

// Avoid
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    // ...
  }
  // ...
}
Enter fullscreen mode Exit fullscreen mode

10. Use Fragment Shorthand

Use the <>...</> shorthand for fragments to avoid additional clutter in your JSX.

// Good
function Group({ children }) {
  return <>{children}</>;
}

// Avoid
function Group({ children }) {
  return <React.Fragment>{children}</React.Fragment>;
}
Enter fullscreen mode Exit fullscreen mode

By adhering to these guidelines,

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player