StackPractices
intermediate By Mathias Paulenko

Container-Presenter: Separate Data Logic from Rendering

How to separate data-fetching logic from rendering in React using the container-presenter pattern. Covers hooks migration, testing benefits, and trade-offs.

Topics: frontend

Overview

The container-presenter pattern splits a React component in two: a container that owns data (fetching, state, business logic) and a presenter that renders UI from props. The container knows where data comes from and what to do with it. The presenter only knows how to draw it. That split is what makes presenters reusable across data sources, testable without mocking the network, and free of side effects.

Dan Abramov named the pattern “Presentational and Container Components” back in 2015, when data logic lived in class components. React 16.8 shipped hooks in 2019 and custom hooks quietly absorbed the container’s job — but the split itself still pays off wherever data logic and markup would otherwise tangle into one file.

When to Use

  • Components that mix data-fetching with non-trivial rendering logic
  • UI components reused with different data sources (featured products, search results, related items)
  • Teams where data logic and UI design are owned by different people
  • Test strategies that need rendering isolated from network dependencies
  • Shared component libraries where consumers bring their own data

When NOT to Use

  • Simple components with no data-fetching — one component is enough
  • Small apps where two files per component buys nothing
  • Greenfield code: custom hooks are the modern way to extract the container side — you rarely need a literal container component today
  • Components where data and rendering are coupled on purpose and never reused

Solution

Custom hook as container (modern approach)

// useUsers.ts — the hook plays the container role
import { useState, useEffect, useCallback, useMemo } from 'react';

interface User {
  id: number;
  name: string;
  email: string;
}

export function useUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch('/api/users');
      setUsers(await response.json());
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchUsers(); }, [fetchUsers]);

  const deleteUser = useCallback(async (userId: number) => {
    setUsers(prev => prev.filter(u => u.id !== userId));
    await fetch(`/api/users/${userId}`, { method: 'DELETE' });
  }, []);

  // Derived view — never filter `users` itself or the full list is lost
  const visibleUsers = useMemo(
    () => users.filter(u => u.name.toLowerCase().includes(query.toLowerCase())),
    [users, query]
  );

  return { users: visibleUsers, loading, error, deleteUser, setQuery, refetch: fetchUsers };
}
// UserList.tsx — presenter consumes the hook's output
import { useUsers } from '../hooks/useUsers';

export function UserList() {
  const { users, loading, error, deleteUser, setQuery } = useUsers();

  if (loading) return <div className="spinner">Loading users...</div>;
  if (error) return <div className="error">Failed to load: {error}</div>;

  return (
    <div className="user-list">
      <input
        type="search"
        placeholder="Search users..."
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {users.map(user => (
          <li key={user.id}>
            <span>{user.name} — {user.email}</span>
            <button onClick={() => deleteUser(user.id)}>Delete</button>
          </li>
        ))}
      </ul>
      {users.length === 0 && <p>No users found.</p>}
    </div>
  );
}

Reusable presenter with different data sources

// ProductGrid.tsx — pure presenter, knows nothing about the API
interface Product {
  id: number;
  name: string;
  image: string;
  price: number;
}

interface ProductGridProps {
  products: Product[];
  loading: boolean;
  error: string | null;
  onAddToCart: (productId: number) => void;
  layout?: 'grid' | 'list' | 'carousel';
}

export function ProductGrid({ products, loading, error, onAddToCart, layout = 'grid' }: ProductGridProps) {
  if (loading) return <div className="skeleton-grid">Loading products...</div>;
  if (error) return <div className="error-banner">{error}</div>;

  return (
    <div className={`product-${layout}`}>
      {products.map(product => (
        <div key={product.id} className="product-card">
          <img src={product.image} alt={product.name} />
          <h3>{product.name}</h3>
          <p className="price">${product.price}</p>
          <button onClick={() => onAddToCart(product.id)}>Add to Cart</button>
        </div>
      ))}
    </div>
  );
}
// FeaturedProducts.tsx — container #1 feeding the same presenter
import { useState, useEffect } from 'react';
import { ProductGrid } from './ProductGrid';

export function FeaturedProducts() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/products?featured=true')
      .then(res => res.json())
      .then(data => { setProducts(data); setLoading(false); })
      .catch(err => { setError(err.message); setLoading(false); });
  }, []);

  const addToCart = (productId: number) => {
    fetch('/api/cart', {
      method: 'POST',
      body: JSON.stringify({ productId, quantity: 1 }),
    });
  };

  return (
    <section className="featured">
      <h2>Featured Products</h2>
      <ProductGrid products={products} loading={loading} error={error}
        onAddToCart={addToCart} layout="carousel" />
    </section>
  );
}
// SearchResults.tsx — container #2, same presenter, different data
export function SearchResults({ query }: { query: string }) {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/products?q=${encodeURIComponent(query)}`)
      .then(res => res.json())
      .then(data => { setProducts(data); setLoading(false); })
      .catch(err => { setError(err.message); setLoading(false); });
  }, [query]);

  const addToCart = (productId: number) => {
    fetch('/api/cart', {
      method: 'POST',
      body: JSON.stringify({ productId, quantity: 1 }),
    });
  };

  return (
    <section className="search-results">
      <h2>Results for "{query}"</h2>
      <ProductGrid products={products} loading={loading} error={error}
        onAddToCart={addToCart} layout="list" />
    </section>
  );
}

Testing the presenter in isolation

This is the payoff: the presenter takes plain props, so tests need no network mocking.

// ProductGrid.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import { ProductGrid } from './ProductGrid';

const mockProducts = [
  { id: 1, name: 'Keyboard', image: '/kb.png', price: 79 },
  { id: 2, name: 'Mouse', image: '/ms.png', price: 39 },
];

const props = {
  products: mockProducts,
  loading: false,
  error: null,
  onAddToCart: jest.fn(),
};

describe('ProductGrid', () => {
  it('renders every product', () => {
    render(<ProductGrid {...props} />);
    expect(screen.getByText('Keyboard')).toBeInTheDocument();
    expect(screen.getByText('Mouse')).toBeInTheDocument();
  });

  it('shows loading state', () => {
    render(<ProductGrid {...props} loading={true} />);
    expect(screen.getByText('Loading products...')).toBeInTheDocument();
  });

  it('shows error message', () => {
    render(<ProductGrid {...props} error="Network error" />);
    expect(screen.getByText('Network error')).toBeInTheDocument();
  });

  it('forwards the product id to onAddToCart', () => {
    render(<ProductGrid {...props} />);
    fireEvent.click(screen.getAllByText('Add to Cart')[0]);
    expect(props.onAddToCart).toHaveBeenCalledWith(1);
  });
});

Classic container with class components (legacy)

You will still find this in older codebases. Same split, but a class owns the state:

// UserListContainer.jsx — class container (pre-hooks style)
import React, { Component } from 'react';
import { UserListPresenter } from './UserListPresenter';

class UserListContainer extends Component {
  state = { users: [], query: '', loading: true, error: null };

  componentDidMount() { this.fetchUsers(); }

  async fetchUsers() {
    this.setState({ loading: true, error: null });
    try {
      const response = await fetch('/api/users');
      this.setState({ users: await response.json(), loading: false });
    } catch (error) {
      this.setState({ error: error.message, loading: false });
    }
  }

  handleDelete = async (userId) => {
    await fetch(`/api/users/${userId}`, { method: 'DELETE' });
    this.fetchUsers();
  };

  // Store the query and filter at render time — filtering `users` in
  // state would destroy the full list after the first keystroke.
  handleSearch = (query) => this.setState({ query });

  render() {
    const { users, query, loading, error } = this.state;
    const visible = users.filter(u =>
      u.name.toLowerCase().includes(query.toLowerCase())
    );
    return (
      <UserListPresenter
        users={visible}
        loading={loading}
        error={error}
        onDelete={this.handleDelete}
        onSearch={this.handleSearch}
      />
    );
  }
}

Explanation

Data flows one way: the container (or hook) fetches and owns state, then passes data plus callbacks down as props. The presenter receives products, loading, error, onAddToCart and renders — it never imports fetch, a store, or a router. Swap the container and the same presenter draws featured products, search results, or a mock fixture in a test.

flowchart diagram: API[(API)

Two details make the split work. First, business state lives above the line: the full user list, filters, and loading flags belong to the container; the presenter may keep UI state (open tab, hovered row) but nothing that survives a data refresh. Second, derived data stays derived — a filtered list is computed at render (or useMemo), never written back into state. The pre-2019 class version used setState for the filtered result and lost the original list on the first keystroke; keeping query in state instead fixes it cleanly.

For load/error state machines that grow past three flags, pair the container with state machines in the UI instead of booleans.

Variants

ApproachState lives inEraUse it when
Custom hook + presenterhookReact 16.8+Default for new code — same split, no wrapper component
Class container + presenterclass componentPre-2019Maintaining legacy codebases
Render prop containercomponent propTransition eraRare today — hooks cover the same ground more simply
HOC containerwrapper componentPre-hooksCross-cutting concerns (auth, tracking); rare for data

Render props as container

// DataContainer.jsx — container delivered as a render prop
import { useState, useEffect } from 'react';

export function DataContainer({ url, render }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(d => { setData(d); setLoading(false); })
      .catch(e => { setError(e.message); setLoading(false); });
  }, [url]);

  return render({ data, loading, error });
}

// Usage — the presenter is inline
<DataContainer url="/api/users" render={({ data, loading, error }) => (
  loading ? <Spinner /> : <UserList users={data} />
)} />

Higher-order component as container

// withData.jsx — HOC wrapping a presenter with data
import { useState, useEffect } from 'react';

export function withData(url, WrappedComponent) {
  return function DataContainer(props) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
      fetch(url)
        .then(res => res.json())
        .then(d => { setData(d); setLoading(false); })
        .catch(e => { setError(e.message); setLoading(false); });
    }, [url]);

    return <WrappedComponent data={data} loading={loading} error={error} {...props} />;
  };
}

// Usage
const UserListContainer = withData('/api/users', UserListPresenter);

Best Practices

  • Keep presenters pure — no side effects, no API calls, no state beyond UI state
  • Pass callbacks, not data sources — presenters get onDelete(id), never a fetch function
  • Type the props — a typed ProductGridProps interface catches container/presenter mismatches at build time
  • Prefer custom hooks over HOCs or render props — they compose better (see custom hook composition)
  • Test presenters in isolation — render with mock props, assert output, verify callbacks; no network mocking needed
  • Keep presenters generic — items/onItemDelete props reuse better than users/onUserDelete
  • If deletes should feel instant, apply the optimistic update pattern — remove the row first, roll back on failure

Common Mistakes

  • Business logic in presenters: validation, transformation, and API calls belong in the container or hook — the presenter only renders.
  • Filtering state destructively: setUsers(users.filter(...)) erases the original list. Keep the source untouched and derive the view with useMemo or render-time filtering.
  • Presenters too specific: a UserList hardwired to /api/users can’t be reused — accept items and onItemDelete instead.
  • Testing through the container: if you mock fetch to test markup, the split is incomplete — test the presenter alone.
  • Splitting trivial components: a button that opens a dropdown doesn’t need two files. Reserve the split for real data logic.

See Also

Frequently Asked Questions

Is container-presenter still relevant with hooks?

Yes, but the container half moved. Custom hooks now hold the data logic and components render the hook's output — same separation, less boilerplate. A literal container component is mostly a legacy-code sighting today.

When should I use container-presenter vs. a single component?

Split when the component has both data-fetching and non-trivial markup, or when the same UI serves different data sources. If it's one straightforward fetch plus a list, a single component with a hook inside is fine.

What's the difference between container-presenter and smart-dumb components?

Same pattern, two names. Container = smart (owns data), presenter = dumb (renders props). Abramov's original article used both terms interchangeably.

Should presenters have any state?

Only UI state — expanded rows, active tab, hover. Anything tied to server data (selected user, filtered list, pagination) belongs in the container or hook.

Should I still use PropTypes?

Only if the codebase already does. For new code, TypeScript interfaces do the same job at compile time and catch more; PropTypes survive mostly in older libraries published without types.

Can I use this pattern with Vue or Angular?

The principle transfers. In Vue, a parent component fetches and a child receives props; in Angular, a smart component injects the service and feeds a dumb component through @Input. Frameworks differ, the separation doesn't.