π§Ή 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 ofsubmit
π§© 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.