Writing Clean React Code
Following best practices helps you write maintainable, scalable React applications. These guidelines come from the React community and real-world production experience.
The key principles are: keep components small and focused, lift state only as high as needed, use composition over inheritance, and write declarative code.
- Keep components small — if a component is over 200 lines, consider splitting it
- One component per file — each file exports a single component
- Use descriptive names — UserProfileCard, not Card2
- Lift state to the nearest common ancestor, not higher
- Use custom hooks to extract reusable logic
- Avoid unnecessary state — derive values from existing state when possible
- Use key props correctly in lists — stable IDs, not indices
- Handle loading and error states in data fetching
- Use TypeScript for type safety in larger projects
- Keep side effects in useEffect, not in event handlers or render logic
Notes
- The best code is the code that is easy to read, understand, and change. Optimize for clarity first, performance second.
Recommended Folder Structure
For medium to large projects, organize components by feature rather than by type. This keeps related code together and makes navigation easier.
Example
src/
├── components/ # Shared/reusable components
│ ├── Button/
│ │ ├── Button.jsx
│ │ ├── Button.module.css
│ │ └── Button.test.jsx
│ └── Header/
├── features/ # Feature-based modules
│ ├── auth/
│ │ ├── LoginForm.jsx
│ │ ├── useAuth.js
│ │ └── authContext.js
│ └── todos/
│ ├── TodoList.jsx
│ ├── TodoItem.jsx
│ └── useTodos.js
├── hooks/ # Shared custom hooks
├── utils/ # Helper functions
├── App.jsx
└── main.jsx Notes
- There's no single right way to structure a React project. Start simple and refactor as your app grows. The goal is to make code easy to find and understand.
