Pattern Components Beginner
Presentational vs. Container
You keep dumb components, which only render their props, separate from smart components that manage data, so the UI is easy to reuse and easy to test.
The problem
You might open a component file to fix a CSS bug and find 800 lines of API calls, error handling, data transformation, and JSX all mixed together, where it’s hard to tell which code affects the styling and which code runs the business logic.
The pattern
With this pattern, you split your components into two types. Presentational components only render UI, and container components fetch data and manage state.
Problem
I’ve reviewed components where changing a button’s color required understanding the entire data fetching pipeline. Designers couldn’t try out UI changes without running a backend, and testing meant mocking every API the component called.
It gets worse when you need to reuse the UI. You’ve built a nice UserList component, but it’s hardwired to one specific API. Now marketing wants the same list design with data from a different endpoint, and you can either copy the component and maintain both versions, or refactor it completely.
Solution
Presentational components are dumb on purpose. They receive data through props and render it, and they don’t do any fetching or business logic, so to test one, you only have to pass it props and check the output.
Container components do everything else. They fetch data, manage state, handle errors, and pass the results down to presentational components, so all of that code stays out of the components that render the UI.
Once UserList only renders the list, you can give it data from any source, such as a REST API, GraphQL, local storage, or a WebSocket. The UI looks the same wherever the data comes from, and its tests don’t need mocks.
In modern React, a custom hook often does the container’s job, and the component that renders the UI still doesn’t fetch its own data.
Example
The first example starts with one component that fetches and renders, and then splits it into a presentational component and a container.
Before the Split
This UserList fetches the users, tracks loading and errors, handles clicks, and renders the list, all in one component.
function UserList() {
const navigate = useNavigate();
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchUsers()
.then(setUsers)
.catch(setError)
.finally(() => setLoading(false));
}, []);
const handleUserClick = async (userId) => {
await trackUserClick(userId);
navigate(`/user/${userId}`);
};
if (loading) return <div className="spinner">Loading...</div>;
if (error) return <div className="error">{error.message}</div>;
if (users.length === 0) return <div className="empty">No users</div>;
return (
<ul className="user-list">
{users.map(user => (
<li key={user.id} onClick={() => handleUserClick(user.id)}>{user.name}</li>
))}
</ul>
);
}
Presentational and Container Pattern
After the split, everything above the first if goes into the container, and everything from that if down stays in UserList. In all three tabs, the presentational component renders the loading, error, and empty states as well as the list, because those are all markup. The container tracks which state the list is in and handles the clicks.
// Presentational - only renders UI
function UserList({ users, onUserClick, loading, error }) {
if (loading) return <div className="spinner">Loading...</div>;
if (error) return <div className="error">{error.message}</div>;
if (users.length === 0) return <div className="empty">No users</div>;
return (
<ul className="user-list">
{users.map(user => (
<li key={user.id} onClick={() => onUserClick(user.id)}>{user.name}</li>
))}
</ul>
);
}
// Container - handles data fetching and state
function UserListContainer() {
const navigate = useNavigate();
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchUsers()
.then(setUsers)
.catch(setError)
.finally(() => setLoading(false));
}, []);
const handleUserClick = async (userId) => {
await trackUserClick(userId);
navigate(`/user/${userId}`);
};
return (
<UserList
users={users}
onUserClick={handleUserClick}
loading={loading}
error={error}
/>
);
} <!-- UserList.vue - Presentational -->
<script setup>
defineProps({ users: Array, loading: Boolean, error: Object });
defineEmits(['user-click']);
</script>
<template>
<div v-if="loading" class="spinner">Loading...</div>
<div v-else-if="error" class="error">{{ error.message }}</div>
<div v-else-if="users.length === 0" class="empty">No users</div>
<ul v-else class="user-list">
<li v-for="user in users" :key="user.id" @click="$emit('user-click', user.id)">
{{ user.name }}
</li>
</ul>
</template><!-- UserListContainer.vue - Container -->
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import UserList from './UserList.vue';
const router = useRouter();
const users = ref([]);
const loading = ref(true);
const error = ref(null);
onMounted(async () => {
try {
users.value = await fetchUsers();
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
});
async function handleUserClick(userId) {
await trackUserClick(userId);
router.push(`/user/${userId}`);
}
</script>
<template>
<UserList :users="users" :loading="loading" :error="error" @user-click="handleUserClick" />
</template> <!-- UserList.svelte - Presentational -->
<script>
let { users, onUserClick, loading, error } = $props();
</script>
{#if loading}
<div class="spinner">Loading...</div>
{:else if error}
<div class="error">{error.message}</div>
{:else if users.length === 0}
<div class="empty">No users</div>
{:else}
<ul class="user-list">
{#each users as user (user.id)}
<li onclick={() => onUserClick(user.id)}>{user.name}</li>
{/each}
</ul>
{/if}<!-- UserListContainer.svelte - Container -->
<script>
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import UserList from './UserList.svelte';
let users = $state([]), loading = $state(true), error = $state(null);
onMount(async () => {
try {
users = await fetchUsers();
} catch (err) {
error = err;
} finally {
loading = false;
}
});
async function handleUserClick(userId) {
await trackUserClick(userId);
goto(`/user/${userId}`);
}
</script>
<UserList {users} {loading} {error} onUserClick={handleUserClick} /> Modern Hooks Alternative
A custom hook can take over the container’s data logic. The fetching and state move into useUsers, and UserList and its props stay exactly as they were. The component that calls the hook is still a container, because it gets the data and passes it to UserList without rendering any markup of its own, but with the hook it’s only a few lines long.
// Custom hook: the data logic that was in the container
function useUsers() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchUsers()
.then(setUsers)
.catch(setError)
.finally(() => setLoading(false));
}, []);
return { users, loading, error };
}
// Still a container, but the hook does most of its work
function UserListContainer() {
const navigate = useNavigate();
const { users, loading, error } = useUsers();
return (
<UserList
users={users}
loading={loading}
error={error}
onUserClick={(id) => navigate(`/user/${id}`)}
/>
);
}
Reusable Presentational Component
Because UserList only depends on its props, a second container can give it users from somewhere else. This one is for the marketing team’s list, which loads its users from a different endpoint and doesn’t track clicks.
function MarketingContactsContainer() {
const navigate = useNavigate();
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchMarketingContacts() // different endpoint
.then(setUsers)
.catch(setError)
.finally(() => setLoading(false));
}, []);
// Same UserList as before
return (
<UserList
users={users}
loading={loading}
error={error}
onUserClick={(id) => navigate(`/contact/${id}`)}
/>
);
}
Testing Presentational Components
If a component only renders its props, testing it is simple, and you don’t need any mocks.
test('renders user list', () => {
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const { getByText } = render(<UserList users={users} />);
expect(getByText('Alice')).toBeInTheDocument();
expect(getByText('Bob')).toBeInTheDocument();
});
test('calls onClick handler', () => {
const handleClick = jest.fn();
const { getByText } = render(
<UserList users={[{ id: 1, name: 'Alice' }]} onUserClick={handleClick} />
);
fireEvent.click(getByText('Alice'));
expect(handleClick).toHaveBeenCalledWith(1);
});
Benefits
- Presentational components work with any data source, such as REST, GraphQL, a WebSocket, or a cache, because nothing in them depends on where the data comes from.
- Testing a presentational component is simple, because you pass it props and check the output without any mocking, and it’s easy to document in Storybook with different combinations of props.
- Designers can work on the UI without understanding the data fetching, and when the API changes, you only have to update the container.
- You can move presentational components between projects, because UserList works anywhere that gives it the right props.
Tradeoffs
- There are more files and more indirection, because each feature needs at least two components, and you might find yourself jumping between them a lot.
- The split is overkill for simple components, such as a button that’s only used in one place.
- You can move the data logic into hooks, so in modern React a container is often only a few lines long, and many teams let the page component call the hook instead of writing a separate container.
- Passing props down gets tedious when a container has fifteen of them to pass.
- The boundary isn’t always clear, such as whether date formatting belongs in the presentational component or the container.
- Many developers now prefer colocation, keeping related code together instead of splitting it up by type.
Summary
With this pattern, you split your UI into dumb components that render props and smart components that manage data. The presentational components are easy to reuse and easy to test, and the containers handle fetching data and managing state. In modern React, hooks now do most of a container’s work, but it’s still useful to keep the code that renders the UI separate from the code that fetches and manages the data.
See also
- Separation of Concerns — Fundamentals
- Single Responsibility — Fundamentals
- Component Testing — Testing
- Smart and Dumb Components - Dan Abramov
- Thinking in React
- Component Design - Vue