FMTechnical notes
Portfolio
Back to the blog

React · Advanced · Manual

Clean Architecture and the Container-Presentational Pattern in React 19 / Next.js

Most teams that say 'we do Clean Architecture' have a folder problem, not an architecture problem. What matters is the direction of dependencies: your business logic shouldn't know React exists.

After reading this
  • Understand why dependency direction matters more than folders in Clean Architecture
  • Implement Container components that orchestrate data and actions, and Presentational components that only receive props
  • Use React 19 Server Components as native containers with hooks like use, useActionState and useFormStatus
01 / 06

What is Clean Architecture Really?

Clean Architecture isn't a folder structure with English names. It's a direction rule: dependencies point inward, toward the domain. The domain doesn't depend on React, Next, or fetch; React, Next, and fetch depend on the domain.

When you invert that direction — when the domain imports React — a framework change forces you to rewrite the logic you were supposedly protecting. The pattern survives because it isolates what changes fast (the UI) from what changes slowly (the business rules). In React, that line lands between containers and presentational.

02 / 06

Basic Container-Presentational

The Container-Presentational pattern separates responsibilities clearly:

- Container components handle state, effects, and actions.

- Presentational components only receive props and return JSX.

tsx
// Presentational Component
const PolicyApprovalView = ({ 
  policies, 
  loading, 
  error,
  onApprove,
  approvingId
}: { 
  policies: Array<{id: string; client: string; amount: number; status: string}>; 
  loading: boolean; 
  error: string | null;
  onApprove: (id: string) => void;
  approvingId: string | null;
}) => (
  <div className="policy-approval-container">
    <h2>Policy Approval</h2>
    {error && <div className="error">{error}</div>}
    {loading ? (
      <p>Loading policies...</p>
    ) : (
      <ul className="policy-list">
        {policies.map(policy => (
          <li key={policy.id} className="policy-item">
            <div>
              <strong>{policy.client}</strong> - ${policy.amount}
            </div>
            <div>Status: {policy.status}</div>
            <button 
              onClick={() => onApprove(policy.id)}
              disabled={approvingId === policy.id}
            >
              {approvingId === policy.id ? 'Approving...' : 'Approve'}
            </button>
          </li>
        ))}
      </ul>
    )}
  </div>
);
03 / 06

React 19 Server Components as Containers

With React 19, Server Components can act as natural containers. They can handle API calls directly without needing useEffect, while child components remain pure.

New hooks like useActionState, useOptimistic and useFormStatus allow orchestrating asynchronous and optimistic operations from the server.

tsx
// Server Component as Container with React 19
import { Suspense } from 'react';
import { getPolicies } from './actions';
import { PolicyApprovalView } from './PolicyApprovalView';

export default async function PolicyApproval() {
  const policies = await getPolicies(); // Direct use of server function
  
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <PolicyApprovalContainer policies={policies} />
    </Suspense>
  );
}

// Client Component Container with useActionState and useOptimistic
'use client';
import { useActionState, useOptimistic } from 'react';
import { approvePolicy } from './actions';
import { PolicyApprovalView } from './PolicyApprovalView';

export function PolicyApprovalContainer({ policies: initialPolicies }: { 
  policies: Array<{id: string; client: string; amount: number; status: string}> 
}) {
  // Optimistic state to show immediate changes
  const [optimisticPolicies, addOptimisticPolicy] = useOptimistic(
    initialPolicies,
    (state, { id, status }: { id: string; status: string }) => 
      state.map(policy => 
        policy.id === id ? { ...policy, status } : policy
      )
  );

  // useActionState for handling form state and actions
  const [state, formAction, isPending] = useActionState(
    async (prevState: { error: string | null }, formData: FormData) => {
      const policyId = formData.get('policyId') as string;
      
      // Optimistic update before the real call
      addOptimisticPolicy({ id: policyId, status: 'approving' });
      
      try {
        const result = await approvePolicy(policyId);
        if (result.success) {
          addOptimisticPolicy({ id: policyId, status: 'approved' });
          return { error: null };
        }
        return { error: result.error };
      } catch (error) {
        return { error: 'Error approving policy' };
      }
    },
    { error: null }
  );

  return (
    <>
      {state.error && <div className="error">{state.error}</div>}
      <form action={formAction}>
        <PolicyApprovalView 
          policies={optimisticPolicies}
          loading={isPending}
          error={state.error}
          onApprove={(id) => {
            const formData = new FormData();
            formData.append('policyId', id);
            formAction(formData);
          }}
          approvingId={isPending ? 'temp' : null}
        />
      </form>
    </>
  );
}
04 / 06

Testing Benefits

The clear separation between Container and Presentational makes testing much easier:

- Presentational components are pure functions and can be easily tested with snapshots or render testing.

- Containers can be tested by mocking dependencies like APIs or stores.

tsx
// Test for Presentational component using React Testing Library
import { render, screen, fireEvent } from '@testing-library/react';
import { vi } from 'vitest';
import { PolicyApprovalView } from './PolicyApprovalView';

describe('PolicyApprovalView', () => {
  const mockPolicies = [
    { id: '1', client: 'John Doe', amount: 10000, status: 'pending' },
    { id: '2', client: 'Jane Smith', amount: 15000, status: 'pending' }
  ];

  it('displays policies correctly', () => {
    render(
      <PolicyApprovalView 
        policies={mockPolicies}
        loading={false}
        error={null}
        onApprove={vi.fn()}
        approvingId={null}
      />
    );

    expect(screen.getByRole('heading', { name: 'Policy Approval' })).toBeInTheDocument();
    expect(screen.getByText('John Doe')).toBeInTheDocument();
    expect(screen.getByText('$10000')).toBeInTheDocument();
  });

  it('calls onApprove when approve button is clicked', () => {
    const mockOnApprove = vi.fn();
    
    render(
      <PolicyApprovalView 
        policies={mockPolicies}
        loading={false}
        error={null}
        onApprove={mockOnApprove}
        approvingId={null}
      />
    );

    fireEvent.click(screen.getAllByText('Approve')[0]);
    expect(mockOnApprove).toHaveBeenCalledWith('1');
  });
});
05 / 06

When NOT to Apply This Pattern

Not every component needs this separation. Blindly applying it can lead to over-engineering:

- Small components without complex logic don't need to be split.

- Leaf components like buttons or icons are usually inherently presentational.

06 / 06

Tradeoffs and Considerations

The Container-Presentational pattern has real costs that must be weighed against its benefits:

- The separation improves testability and reusability but can unnecessarily increase complexity in simple components.

- React 19 reduces the need for traditional client containers thanks to Server Components that can handle data directly.

- New hooks like useActionState and useOptimistic offer more declarative ways to handle state and optimistic updates.

  • Use the pattern when there's significant logic to separate
  • Prioritize readability and maintainability over following dogmas
  • React 19 reduces the need for traditional client containers
Component tree● interactive

Layout-level composition. Owns the document structure and orchestrates which features render.

Practice

Refactor a coupled component

Take a React component that handles both data and rendering in one place, and separate it into Container and Presentational following the explained pattern.

Show a hint

First identify which parts handle state/APIs (Container) and which only display data (Presentational)