Design and Implement a 2x3 React Post Grid with API Integration
System DesignModel answerLast updated
Build a 2x3 React grid component for display feeds, integrate data loading with proper state management, and explain React hook mechanics.
In a live technical screen, you are asked to design and implement a React component that renders a social feed as a fixed $2 \times 3$ grid (2 rows, 3 columns of equal width). Each feed item includes the following properties:
| Field | Description |
|---|---|
feed_id | Unique string identifier |
feed_text | Text content of the post |
createdAt | ISO 8601 timestamp string representing post creation time |
The problem must be solved in three stages:
Part 1: Static Grid Layout
Create a clean component hierarchy (e.g., Grid Container and Post Card) rendering hardcoded dummy data into a 6-cell layout ($2 \times 3$). Ensure that long post texts do not break the strict cell dimensions and equal column widths. Handle scenarios where fewer than 6 posts exist.
Part 2: API Integration & Async Logic
Replace the static data with dynamic fetching from a mock API endpoint (GET /api/v1/feed).
- Display state logic: render loading spinners, network/HTTP error states, and empty states gracefully.
- Data ordering & truncation: ensure exactly 6 items are displayed, ordered by
createdAtdescending (newest first). - Robustness: handle race conditions and prevent state updates on unmounted components using proper effect cleanups (e.g.,
AbortController).
Part 3: Deep Dive on React Hooks
Provide a comprehensive explanation of the React hooks utilized in your implementation (useState, useEffect, useCallback/useMemo, useRef), detail their lifecycles, discuss common pitfalls (such as stale closures), and demonstrate how to extract the fetching logic into a reusable custom hook (useFeedData).
Hints
Hint 1
For fixed 2x3 layouts, CSS Grid with `grid-template-columns: repeat(3, 1fr)` and fixed cell aspect ratio or `minmax` works best.
Hint 2
Remember to pass an `signal` from an `AbortController` into `fetch` inside `useEffect` and invoke `.abort()` in the cleanup function to prevent memory leaks and race conditions.
Hint 3
Ensure HTTP error status codes (e.g., 4xx, 5xx) are manually checked using `response.ok`, as `fetch` only rejects on network failures.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural & Implementation Overview
A complete solution requires splitting concerns between layout structure, CSS isolation, asynchronous state handling, and custom hook abstractions.
Part 1 & Part 2: Code Implementation
1. Custom Hook (useFeedData.js)
import { useState, useEffect } from 'react';
export const useFeedData = (endpoint) => {
const [items, setItems] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const fetchData = async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch(endpoint, { signal });
if (!response.ok) {
throw new Error(`HTTP Error status: ${response.status}`);
}
const data = await response.json();
// Sort by newest first and pick top 6
const sortedData = [...data]
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
.slice(0, 6);
setItems(sortedData);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message || 'Failed to fetch feed data');
}
} finally {
if (!signal.aborted) {
setIsLoading(false);
}
}
};
fetchData();
return () => {
controller.abort();
};
}, [endpoint]);
return { items, isLoading, error };
};
2. Layout Components (FeedGrid.jsx)
import React from 'react';
import { useFeedData } from './useFeedData';
import './FeedGrid.css';
const FeedCard = ({ item }) => {
if (!item) {
return <div className="feed-card empty-cell" />;
}
const formattedDate = new Date(item.createdAt).toLocaleString(undefined, {
dateStyle: 'medium',
timeStyle: 'short',
});
return (
<article className="feed-card">
<p className="feed-text">{item.feed_text}</p>
<time className="feed-date" dateTime={item.createdAt}>
{formattedDate}
</time>
</article>
);
};
export const FeedGrid = ({ apiEndpoint }) => {
const { items, isLoading, error } = useFeedData(apiEndpoint);
if (isLoading) {
return <div className="status-container">Loading feed items...</div>;
}
if (error) {
return <div className="status-container error-state">Error: {error}</div>;
}
// Ensure 6 slots are rendered even if items < 6
const gridSlots = Array.from({ length: 6 }, (_, index) => items[index] || null);
return (
<div className="grid-container">
{gridSlots.map((item, index) => (
<FeedCard key={item ? item.feed_id : `empty-${index}`} item={item} />
))}
</div>
);
};
3. Styling (FeedGrid.css)
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 1fr);
gap: 16px;
width: 100%;
max-width: 900px;
margin: 0 auto;
}
.feed-card {
box-sizing: border-box;
background-color: #ffffff;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 16px;
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 140px;
overflow: hidden;
}
.empty-cell {
background-color: #f9f9f9;
border-style: dashed;
}
.feed-text {
margin: 0 0 12px 0;
font-size: 14px;
line-height: 1.4;
/* Multi-line truncation */
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
.feed-date {
font-size: 12px;
color: #666666;
align-self: flex-end;
}
.status-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 200px;
font-size: 16px;
}
.error-state {
color: #d32f2f;
}
Part 3: Deep Dive into React Hooks & Mechanics
1. Fundamental Hooks Used
useState: Used to track asynchronous state across rendering cycles (items,isLoading,error). Updating state triggers a re-render of the component with fresh data.useEffect: Encapsulates side effects (network operations). By declaring[endpoint]in the dependency array, the effect executes on mount and wheneverendpointchanges.
2. Lifecycle & Effect Cleanup Mechanics
When asynchronous operations occur inside useEffect, component unmounting or rapid prop changes create race conditions.
- The Problem: If a request resolves after the component unmounts, calling
setStatecauses memory leaks and warnings in older React versions, or redundant state updates in React 18+. - The Solution: Using
AbortController. The cleanup function returned byuseEffectexecutes before re-running the effect or upon unmounting. Callingcontroller.abort()cancels the fetch request in flight.
3. Advanced Hook Concepts & Edge Cases
-
useMemovs.useCallback:useMemocaches the calculated result of an expensive operation across renders (e.g., sorting 10,000 array items before slicing).useCallbackcaches a function instance between renders to preserve referential equality when passing callbacks to optimized child components usingReact.memo.
-
Stale Closures:
- A stale closure occurs when a callback or effect captures state/prop variables from a previous render pass due to an incomplete dependency array.
- Example: If an effect references a variable inside its closure without listing it in the dependency array, it will forever read the initial render's value.
-
Rules of Hooks:
- Call hooks only at the top level of React components or custom hooks. Do not call them inside loops, conditions, or nested functions to ensure hook call order stays consistent across renders.
- Call hooks only from React function components or custom hooks.
Complexity Analysis
- Time Complexity:
- Sorting $N$ feed items: $\mathcal{O}(N \log N)$ where $N$ is the total items returned by the API.
- Slicing and rendering 6 items: $\mathcal{O}(1)$.
- Space Complexity:
- Memory storage for input items and rendered DOM nodes: $\mathcal{O}(N)$ space to load the JSON response payload.