SmartCodingTips

🧹 Writing Clean Code in React

Clean code is not just about formatting β€” it’s about writing readable, maintainable, and scalable code that others (and future-you) can understand. Here's how to do it in React.


πŸ”€ 1. Meaningful Naming

  • Name components with PascalCase
  • Use camelCase for variables and functions
  • Use descriptive prop names like onLogin instead of submit

🧩 2. Keep Components Small

Split large components into smaller reusable ones. Each component should do **one thing** well.

πŸ“¦ 3. Organize Code by Feature

  • Use a feature-based folder structure
  • Group related components, styles, hooks, and context together

🧠 4. Use Functional Components + Hooks

Prefer function components with hooks over class components for consistency and cleaner code.

πŸ” 5. Avoid Repetition (DRY)

  • Extract common logic into reusable hooks
  • Create reusable UI components
  • Move repeated API logic into a service file

πŸ§ͺ 6. Use PropTypes or TypeScript

Validate props using PropTypes or adopt TypeScript to prevent bugs and improve developer experience.

🚫 7. Avoid Inline Logic in JSX

Move conditions, mapping, and calculations out of the return block. Example:


// ❌ Bad
return <div>{items.map(i => <Item key={i.id} />)}</div>

// βœ… Good
const renderedItems = items.map(i => <Item key={i.id} />);
return <div>{renderedItems}</div>;

🧼 8. Clean Up useEffect

Always clear subscriptions, intervals, and side effects to avoid memory leaks:


useEffect(() => {
  const interval = setInterval(() => {
    console.log("tick");
  }, 1000);

  return () => clearInterval(interval);
}, []);

🧰 9. Use ESLint + Prettier

Install and configure eslint and prettier to maintain code quality and style automatically.

βœ… 10. Comment When Necessary

Avoid obvious comments. Instead, comment only on complex logic or business rules that aren't self-evident.