Writing clean React code isn't just about making things work โ itโs about readability, maintainability, and scaling your components.
Hereโs a simple visual cheatsheet that highlights best practices for building better React components.
โ Doโs & Donโts
๐ธ Props
โ Bad:
<MyButton txt="Click" col="blue" />
โ
Good:
<MyButton label="Click" color="primary" />
๐ก Use meaningful, descriptive prop names.
๐ธ Conditional Rendering
โ Bad:
{!isLoading ? <Data /> : null}
โ
Good:
{isLoading && <Spinner />}
๐ก Use early returns and avoid nesting where possible.
๐ธ Folder Structure
โ Bad:
/components
Button.js
Card.js
Modal.js
โ
Good:
/components
/Button
index.tsx
styles.module.css
types.ts
๐ก Organize by component, not by file type.
๐ธ Logic Separation
โ Bad:
const fetchData = async () => {
const res = await fetch(...);
const data = await res.json();
setState(data);
};
โ
Good:
import { getUserData } from '@/services/user';
const user = await getUserData();
setUser(user);
๐ก Keep logic in services or hooks. Components should be mostly UI.
๐ธ useEffect Usage
โ Bad:
useEffect(() => {
window.addEventListener('resize', handleResize);
}, []);
โ
Good:
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
๐ก Always clean up your effects to avoid memory leaks.
๐ Final Tip
Clean code in React isnโt just for you โ itโs for your teammates, your future self, and the community. Refactor small, commit often, and prioritize clarity over cleverness.
Top comments (0)