React Component Refactoring Best Practices
When to Refactor
You should consider refactoring a React component when any of the following occur:
- File is too long
- Components exceeding
~200β300 linesare candidates for splitting. - Too many responsibilities (SRP violation)
- Components handling UI, state logic, data fetching, and event handling together.
- Hard to test or reuse
- Code duplication or difficulty in unit testing parts of the component.
- Deeply nested JSX
- More than 3β4 levels of nesting signals a need to split into subcomponents.
- Multiple unrelated hooks
- Several
useStateoruseEffecthooks doing different tasks in one file.
Recommended File Size
| Component Type | Typical Size (Lines) |
|---|---|
| Small UI Component | 50β100 |
| Medium Component | 100β200 |
| Large Page / Screen | 200β300 |
| Anything >300 lines | Should be split |
Focus on readability and maintainability rather than strict line limits.
Strategies for Refactoring
1. Separate Logic and UI
Move business logic or stateful logic into custom hooks.
// useFormLogic.js
export const useFormLogic = () => {
const [value, setValue] = useState("");
const handleChange = (e) => setValue(e.target.value);
return { value, handleChange };
};
// Form.js
const Form = () => {
const { value, handleChange } = useFormLogic();
return <input value={value} onChange={handleChange} />;
};
2. Split into Smaller Components
Break large JSX into presentational subcomponents.
const UserProfileHeader = ({ user }) => <h1>{user.name}</h1>;
const UserProfileDetails = ({ user }) => <p>{user.email}</p>;
const UserProfile = ({ user }) => (
<>
<UserProfileHeader user={user} />
<UserProfileDetails user={user} />
</>
);
3. Organize with Folders
UserProfile/
βββ UserProfile.js // Main component
βββ UserProfileHeader.js // Subcomponent
βββ UserProfileDetails.js // Subcomponent
βββ useUserProfile.js // Custom hook
4. Extract Constants and Styles
Move colors, validation rules, mock data, and styles to separate files.
General Best Practices
- Keep components focused on rendering UI only.
- Use custom hooks for stateful logic.
- Use presentational components for UI parts.
- Follow SRP, DRY, KISS principles.
Rule of Thumb: If a file is βtoo long to scroll comfortablyβ or βhard to understand at a glance,β it should be refactored.