Container/presentational component
Defination
Container/Presentational pattern separates React components into:
- Containers: Handle logic, data fetching, and state
- Presentational: Focus on UI rendering, receive data via props
code
// Container Component
import React, { useState, useEffect } from "react";
import UserList from "./UserList";
const UserListContainer = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
// Fetch users from API
fetchUsers().then((data) => setUsers(data));
}, []);
return <UserList users={users} />;
};
// Presentational Component
const UserList = ({ users }) => (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
export { UserListContainer, UserList };
Pros and Cons
Pros:
- Separates logic from UI
- Reusable components
- Easier testing
- Flexible for changes
Cons:
- More complex structure
- Potential prop drilling
- Possible performance impact
- Steeper learning curve