Skip to content

Refactoring a Large React Component: Find the Seams Before You Split

A workflow for breaking apart a 500-line React component: find the seams, extract hooks, split the render, move pure logic out. Type-checked code.

· · 10 min read

Updated: November 25, 2026

React UserDashboard component holding five useState calls before it is split into hooks and parts

Quick Take

Large React components get messy because nobody defined the seams first. Find where data fetching, form state, validation, and rendering split before you move anything, whether you do the moving or an agent does, or you'll just get 500 lines rearranged into new files. Extract hooks before splitting render, use explicit TypeScript prop interfaces, and start with one seam: run tsc, fix what breaks, then move to the next.

Refactoring a large React component is the process of identifying the boundaries between mixed responsibilities in a bloated component, then mechanically extracting hooks, sub-components, and pure functions along those boundaries. You know how this starts. A UserDashboard component that was 50 lines six months ago. Now it's 500. State declarations at the top, a useEffect that fetches user data and updates three different state variables, a form with validation logic inline, and three visual sections that all read from the same sprawling local state.

This guide used to be framed around AI tools. It never showed a recorded run of one, so that framing is gone, and what's left is the React part, which holds whoever does the typing. The form hook, the validator and the settings section were type-checked together with TypeScript 7.0.2 against @types/react 19.3.3 on November 25, 2026.

Does it matter who moves the code? Less than you'd think. Hand the whole file to an assistant and say "make this cleaner" and you've skipped the same decision you'd skip by dragging blocks into new files yourself. Architecture requires a decision somebody has to make first.

That decision is where the seams are. Once you've made it, do the extraction or delegate it.

Splitting a component is mechanical. Deciding where the seams are isn't, and no amount of moving code around makes that decision for you.

Share this Post on X Bluesky

Check the quality framework for how this fits into a broader TypeScript code health strategy.

What Is a "Seam" in a React Component?

A seam is a boundary where two distinct responsibilities touch inside one file. In React components, the most common seams are: state logic sitting next to render logic, data fetching tangled with display, and form handling mixed with validation. Identifying seams is quick, and it saves you from a split that only spreads the tangle across more files.

Custom hook is a JavaScript function whose name starts with use and that can call other React hooks internally, letting you extract and reuse stateful logic, like data fetching or form handling, across components without duplicating it. Prop drilling is the pattern of passing a value through several layers of components that don't use it themselves, purely so a deeply nested child can access it.

Ask three questions before you touch any code:

  • What state could live in a custom hook instead of this component?
  • What sections of JSX could be their own components without needing to share state?
  • What logic (validation, calculations, transforms) doesn't actually need React at all?

Here's what a tangled component looks like in practice. This is pseudo-code, but the shape is a common one:

// UserDashboard.tsx, ~500 lines, before
function UserDashboard({ userId }: { userId: string }) {
  const [user, setUser]             = useState<User | null>(null);
  const [loading, setLoading]       = useState(true);
  const [formData, setFormData]     = useState({ name: '', email: '' });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [activeTab, setActiveTab]   = useState('profile');

  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(r => r.json())
      .then(data => { setUser(data); setLoading(false); });
  }, [userId]);

  function handleSubmit(e: React.SubmitEvent<HTMLFormElement>) {
    e.preventDefault();
    const errors: Record<string, string> = {};
    if (!formData.name.trim()) errors.name = 'Name is required';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email))
      errors.email = 'Invalid email';
    if (Object.keys(errors).length) { setFormErrors(errors); return; }
    fetch(`/api/users/${userId}`, { method: 'PATCH', body: JSON.stringify(formData) });
  }

  // ... 400 more lines of JSX, tab logic, and a settings form
}

A note on the handler type. Older tutorials, including the first version of this one, type it as React.FormEvent. Current @types/react (19.3) marks that type as deprecated, with a comment that it doesn't actually exist, and points to SubmitEvent for form submits. Use React.SubmitEvent<HTMLFormElement> and your editor stops striking it through.

Three seams are visible immediately. Data fetching with loading state. Form state with validation. And two or three distinct visual sections that share almost no state.

Extract custom hooks first

Data fetching logic, form state, and complex derived calculations all belong in hooks, not because it's a rule, but because moving them there forces the component to declare exactly what it needs. Dan Abramov makes a related point in Writing Resilient Components (2019): a resilient component is always ready to render again with new inputs, and state that belongs to one piece of UI stays local to it. A hook that returns { user, loading, error } makes those inputs and outputs explicit.

Extract hooks before splitting render. If you split render first, the new sub-components still depend on the same tangled state from the parent. You're just spreading the coupling across files instead of fixing it.

Here's the useUserProfile hook extracted from the component above:

// hooks/useUserProfile.ts
interface UseUserProfileReturn {
  user: User | null;
  loading: boolean;
  error: string | null;
}

function useUserProfile(userId: string): UseUserProfileReturn {
  const [user, setUser]       = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError]     = useState<string | null>(null);

  useEffect(() => {
    let ignore = false;
    setLoading(true);
    setError(null);
    fetch(`/api/users/${userId}`)
      .then(r => {
        if (!r.ok) { throw new Error(`HTTP ${r.status}`); }
        return r.json() as Promise<User>;
      })
      .then(data => { if (!ignore) { setUser(data); setLoading(false); } })
      .catch((err: Error) => { if (!ignore) { setError(err.message); setLoading(false); } });
    return () => { ignore = true; };
  }, [userId]);

  return { user, loading, error };
}

The component now calls const { user, loading } = useUserProfile(userId) and the fetch logic is gone from its body, into a hook you can test on its own. The ignore flag is the part the original never had: when userId changes mid-request, the cleanup marks the old request stale, so a slow response for the previous user can't overwrite the new one. That's the pattern the React docs show for fetching in an Effect. The r.ok check turns a 404 or 500 into an error instead of a user built from an error body, and setError(null) clears the last user's error.

One rule for this step: the hook exposes what the component already uses, and nothing more. No retry option, no cache, no onSuccess callback the original never had. Those may be good ideas. They're a separate change with its own review.

If an agent does the extraction, say that out loud. I've used Claude Code daily for over a year, and doing more than it was asked is the habit I correct most often, so I put the limit in the request ("only expose what the component uses, add no new abstractions") and then check the diff for it anyway.

Splitting the render into sub-components

After hooks are extracted, look at the JSX. Render sections that share no state, meaning they don't read from the same useState variables, are good candidates for extraction. The React docs frame this as separation of concerns: a component should ideally be concerned with one thing, and a component that grows gets decomposed into smaller ones. That's the test I apply.

Explicit TypeScript prop types matter here, because they are the contract between the pieces. If writing the props interface feels awkward, the split is probably wrong.

// components/UserProfileSection.tsx
interface UserProfileSectionProps {
  user: User;
  onEditClick: () => void;
}

function UserProfileSection({ user, onEditClick }: UserProfileSectionProps) {
  return (
    <section>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
      <button onClick={onEditClick}>Edit profile</button>
    </section>
  );
}

// components/UserSettingsSection.tsx
interface UserSettingsSectionProps {
  userId: string;
  defaultEmail: string;
}

function UserSettingsSection({ userId, defaultEmail }: UserSettingsSectionProps) {
  const { formData, formErrors, handleSubmit } = useProfileForm(userId, defaultEmail);
  return (
    <form onSubmit={handleSubmit}>
      {/* ... */}
    </form>
  );
}

useProfileForm is the second hook, and it follows the same rule as the first: form state and the submit handler move out, the validation itself goes one step further (next section).

// hooks/useProfileForm.ts
interface UseProfileFormReturn {
  formData: UserFormData;
  formErrors: Record<string, string>;
  setField: (field: keyof UserFormData, value: string) => void;
  handleSubmit: (e: React.SubmitEvent<HTMLFormElement>) => void;
}

function useProfileForm(userId: string, defaultEmail: string): UseProfileFormReturn {
  const [formData, setFormData]     = useState<UserFormData>({ name: '', email: defaultEmail });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  function setField(field: keyof UserFormData, value: string) {
    setFormData(prev => ({ ...prev, [field]: value }));
  }

  function handleSubmit(e: React.SubmitEvent<HTMLFormElement>) {
    e.preventDefault();
    const result = validateUserForm(formData);
    setFormErrors(result.errors);
    if (!result.valid) { return; }
    void fetch(`/api/users/${userId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData),
    });
  }

  return { formData, formErrors, setField, handleSubmit };
}

Two rules for the sub-components. Explicit props, no object spreading: {...props} hides dependencies and makes the contract invisible to anyone reading the component later. And nothing imported from the parent's scope.

See TypeScript clean code patterns for naming conventions and interface design that scale as you add more components.

Logic that doesn't need React at all

This is the step most refactoring guides skip. Validation, calculations, and transformations that don't need React state are better off as plain TypeScript functions rather than hooks or components. My view: this step often does more for readability than splitting components, and it's the easiest one to overlook.

// utils/validateUserForm.ts
interface UserFormData {
  name: string;
  email: string;
}

interface ValidationResult {
  valid: boolean;
  errors: Record<string, string>;
}

function validateUserForm(data: UserFormData): ValidationResult {
  const errors: Record<string, string> = {};
  if (!data.name.trim())
    errors.name = 'Name is required';
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email))
    errors.email = 'Invalid email address';
  return { valid: Object.keys(errors).length === 0, errors };
}

Pure functions have clear input and output types. No component state bleeds into them. They're trivial to unit test without mocking React context or rendering anything.

Why does this matter for real teams? It's common for a React codebase to end up with the same email validation regex copied into several components. Once it's a standalone function with a clear signature, it gets reused. The component just calls validateUserForm(formData).

The three refactor phases side by side

Extract hooksSplit renderMove logic out
TargetData fetching, form stateJSX sections sharing no stateValidation, calculations, transforms
OutputCustom hook, e.g. useUserProfileSub-component with explicit propsPlain TypeScript function
OrderFirstSecondAnytime, easy to overlook
ConstraintExpose only what the component usesNo object spreading, no implicit dependenciesClear input and output types

Knowing when the refactor is done

TypeScript catches most regressions automatically. Missing props, wrong types, unused state, these surface at compile time during the split, not three weeks later in production. That's the real argument for explicit prop interfaces: you can't quietly drop a required field.

The refactor is complete when you can verify three things:

  • Each file has one responsibility you can describe in a sentence without "and"
  • No prop drilling goes deeper than two levels
  • Every custom hook works in isolation, writable as a test without rendering a parent component

Here's the order to run through on a real component:

  1. Ask the three seam questions above and write down every seam you find, even ones you won't extract yet.
  2. Extract data-fetching and derived-state hooks first, since sub-components will depend on their return values next.
  3. Split the JSX into sub-components along the seams that share no state, with explicit TypeScript prop interfaces for each.
  4. Move validation, calculations, and transforms that don't touch React state into plain TypeScript functions.
  5. Run tsc --noEmit after every single step, not just at the end, so you know exactly which extraction broke something.

What does the compiler not tell you? Whether the split was the right one. TypeScript catches structural errors; a mixed concern that type-checks, like a fetch call left in a render function, still needs a reader.

Pair this with automated quality gates and AI review in your CI pipeline to catch regressions on every pull request.


Split a 500-line component without a plan and you get a pile of new files, technically separate, with the same tangled dependencies spread across more imports. The seam identification step is the part that requires you.

A few minutes asking those three questions upfront saves a lot of untangling afterward.

Start with one seam: extract one hook, run the TypeScript compiler, and fix what it reports before you move to the next seam.

Frequently Asked Questions

Can an AI tool do this refactor for me?
It can do the mechanical part once you've named the seams: which state moves into a hook, which render sections are independent, which logic needs no React at all. This guide doesn't show a recorded agent run, so it makes no claim about how well any tool does it. The one first-hand note is from daily use of Claude Code: it tends to do more than it was asked, so state what must not change and read the whole diff.
How do I know when a React component is too large?
A component needs splitting when it mixes concerns you can name separately: data fetching, form state, validation logic, and multiple distinct UI sections. File length is a rough signal, anything past 200 lines usually has at least two extractable responsibilities. The stronger test is whether you can write a single sentence describing what the component does. If that sentence needs and more than once, it's doing too much.
What should a custom hook extracted from a component return?
Only what the component actually uses. The useUserProfile hook in this guide returns user, loading and error and nothing else, and useProfileForm returns the form data, the errors, one setter and the submit handler. Optional parameters, retry logic and generic types the original component never needed are a second change, not part of the refactor.
Should I use TypeScript when splitting React components?
Yes, and you'll feel the benefit immediately. Explicit prop interfaces for each new sub-component force you to define the contract between pieces. If you can't write the props type cleanly, the split is wrong. TypeScript also catches a whole class of regressions during refactoring, a missing prop or wrong type surfaces at compile time, not in production.