ReactEasy
Container vs Presentational?
The container/presentational pattern splits a feature into a container component that owns data, state and side effects, and a presentational component that receives everything as props and only renders. It is the same idea as smart vs dumb components; today the container role is usually played by a custom hook or a Server Component.
Responsibilities
| Container | Presentational |
|---|---|
| fetches data, subscribes to stores | renders markup and styles |
| handles business logic and mutations | raises events via callback props |
| knows routing, auth, APIs | knows nothing about data sources |
| few or no styles | most of the styling |
Benefits
- Presentational components are reusable and trivially testable with props.
- Visual changes do not touch data logic and vice versa.
- Storybook stories can show every state (empty, loading, error) with fake props.
How it looks in modern React
- Custom hook as the container:
const { todos, addTodo } = useTodos()inside a component that renders<TodoList todos={todos} onAdd={addTodo} />. - Server Component as the container: fetch data on the server, render a Client Component with the data (Next.js, React Router RSC).
- Route loaders as the container: React Router loaders fetch data; the route component reads it with
useLoaderDataand renders presentational children.
Avoid over-engineering
Not every component needs a pair. Split when the logic is complex or the UI is reused with different data.
Code example
tsx
1// Presentational2type Todo = { id: string; title: string; done: boolean };34export function TodoListView({ todos, onToggle }: { todos: Todo[]; onToggle: (id: string) => void }) {5 return (6 <ul>7 {todos.map((t) => (8 <li key={t.id}>9 <label>10 <input type="checkbox" checked={t.done} onChange={() => onToggle(t.id)} /> {t.title}11 </label>12 </li>13 ))}14 </ul>15 );16}1718// Container logic as a custom hook19import { useState } from "react";2021function useTodos(initial: Todo[]) {22 const [todos, setTodos] = useState(initial);23 const toggle = (id: string) => setTodos((ts) => ts.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));24 return { todos, toggle };25}2627// Thin container component wiring them together28export function TodoListContainer() {29 const { todos, toggle } = useTodos([{ id: "1", title: "Write docs", done: false }]);30 return <TodoListView todos={todos} onToggle={toggle} />;31}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.