Skip to content

React Component Refactoring Best Practices

When to Refactor

You should consider refactoring a React component when any of the following occur:

  1. File is too long
  2. Components exceeding ~200–300 lines are candidates for splitting.
  3. Too many responsibilities (SRP violation)
  4. Components handling UI, state logic, data fetching, and event handling together.
  5. Hard to test or reuse
  6. Code duplication or difficulty in unit testing parts of the component.
  7. Deeply nested JSX
  8. More than 3–4 levels of nesting signals a need to split into subcomponents.
  9. Multiple unrelated hooks
  10. Several useState or useEffect hooks doing different tasks in one file.

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.