How to implement the Container and Presentational pattern
· Category: React
Short answer
Container components handle data, state, and logic. Presentational components receive props and render UI, remaining free of side effects.
How it works
Containers fetch data, manage state, and pass derived values down. Presentational components focus on layout, styling, and user interaction callbacks. This separation makes UI components easier to test and reuse.
Example
function UserListContainer() {
const [users, setUsers] = useState([]);
useEffect(() => { fetchUsers().then(setUsers); }, []);
return <UserList users={users} />;
}
function UserList({ users }) {
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
Tips
- With hooks, this pattern is less formal; custom hooks often replace containers.
- Still useful for separating complex logic from markup in large components.