React
/Intermediate
Container vs Presentational
Definition
A classic React architecture pattern separating components into two categories: Containers (which handle data fetching and state) and Presentational components (which only render UI based on props).
Explain Like I'm New
Imagine a restaurant. The Container component is the Chef in the kitchen: gathering ingredients, cooking the food, and managing the chaos. The Presentational component is the Waiter: they don't know how to cook, they just take the finished plate (Props) and present it nicely to the customer on the table (UI).
Real World Example
A `UserProfileContainer.js` component executes `useEffect` to fetch user data, and then returns `<UserProfile data={userData} />`. The `UserProfile.js` is a pure function that just renders HTML.
Common Use Cases
- •Separating concerns (Logic vs UI)
- •Making UI components highly reusable across different data sources
- •Making UI components easily testable with Snapshot testing
Interactive Example
// --- MODERN APPROACH (Using Custom Hooks instead of Containers) --- // This has largely replaced the Container/Presentational pattern. // 1. The Logic (Extracted into a Custom Hook) function useUserData(userId) { const [data, setData] = useState(null); useEffect(() => { fetchUser(userId).then(setData); }, [userId]); return data; } // 2. The Component (Cleanly handles both UI and calls the logic) export default function UserProfile({ userId }) { const data = useUserData(userId); if (!data) return <p>Loading...</p>; return <div>{data.name}</div>; }
Interview Questions
basic
- What is a Presentational Component?
- What is a Container Component?
intermediate
- Why is this pattern less common today than it was in 2018?
- Can Presentational components have state?
advanced
- How did React Hooks largely replace the need for Container components?
- When is it still a good idea to use this pattern?