React Community Board: Voting, Re-Ranking, and Sticky Posts
System DesignModel answerLast updated
Build a React feed where upvotes and downvotes re-sort posts by score and designated sticky posts always stay above the ranked list.
React Community Board: Voting, Re-Ranking, and Sticky Posts
You have two hours to build a community board page in React. The board displays a list of posts fetched from a mock API (or a local JSON file). You need to implement two interactive features on top of that list.
Feature 1 — Voting and live re-ranking
Every post has an upvote button and a downvote button. Clicking either one updates the post's score and immediately re-sorts the entire list in descending score order.
Voting rules to handle:
- Clicking the same vote direction a second time undoes the vote (score returns to where it was).
- Clicking the opposite direction switches the vote (net change is ±2, not ±1).
- A user can hold at most one vote per post at any time.
Feature 2 — Sticky posts
Any post can be marked sticky. A sticky post is always rendered above all non-sticky posts, regardless of score. If multiple posts are sticky, they are ordered among themselves by the same descending-score rule. Non-sticky posts continue to sort by score below them.
Before you start coding, think through these questions
- What data shape for each post makes a vote update a small, local change without reconstructing the whole list?
- When you re-sort, how do you break ties deterministically so the list does not flicker?
- When a post jumps position after a vote or a sticky toggle, what happens to keyboard focus and scroll position? How would you handle that?
- If votes and sticky state are persisted to a server, how do you keep the UI responsive while the request is in flight? What do you do if the request fails?
What your implementation should demonstrate
Part 1 — Feed with voting
- A state shape that makes individual post updates cheap and immutable
- Correct score arithmetic for all three vote transitions: new vote, undo, and switch
- A stable, deterministic sort that does not cause unnecessary re-renders
- Accessible controls: buttons with clear labels, visible focus states, and score announced to screen readers
Part 2 — Sticky behaviour
- A composited sort that puts sticky posts first, then ranks each group independently by score
- Correct behaviour when a sticky post is voted on (it stays in the sticky section, but its relative order within that section may change)
- A considered answer to what should happen to focus when the list reorders
Bonus (discuss, don't necessarily code)
- Optimistic UI: apply the vote locally before the server responds
- Rollback: revert to the previous state if the server returns an error
- Debounce or queue strategy if a user clicks rapidly
Hints
Hint 1
Model each post's vote state as a field like `userVote: 'up' | 'down' | null` stored directly on the post object in your array. The score delta on any new click is then just a function of the current `userVote` and the button pressed — no extra bookkeeping needed outside the post itself.
Hint 2
Derive the sorted list with `useMemo` rather than storing a separate sorted copy in state. Split posts into sticky and non-sticky, sort each group by score (breaking ties by a stable secondary key like creation timestamp or id), then concatenate. This way your source-of-truth state stays flat and easy to update immutably.
Hint 3
For accessibility, give each vote button a descriptive `aria-label` (e.g. "Upvote — currently 42 points") and wrap the score in a `<span aria-live="polite">` so screen readers announce changes. For focus-on-reorder, capture the focused post's id before the update and restore focus to that element after React re-renders using a `useEffect` with a ref.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is less about algorithmic complexity and more about getting state shape, derived data, and accessibility right simultaneously. A strong answer walks through those three concerns in order before touching the keyboard.
State shape
The core insight is that voting should update exactly one post and nothing else. That points to a flat array of post objects where each post owns its own vote state:
interface Post {
id: string;
author: string;
body: string;
createdAt: number; // Unix ms — used as a stable tie-breaker
baseScore: number; // score from the server, never mutated client-side
userVote: 'up' | 'down' | null;
sticky: boolean;
}
// Derived, not stored:
// displayScore = baseScore + (userVote === 'up' ? 1 : userVote === 'down' ? -1 : 0)
Keeping baseScore and userVote separate makes rollback trivial: you just restore the old userVote without touching anything else.
Vote arithmetic
There are exactly three cases when a vote button is clicked:
Current userVote | Button clicked | New userVote | Score delta |
|---|---|---|---|
null | up | 'up' | +1 |
'up' | up (same) | null | −1 (undo) |
'down' | up (opposite) | 'up' | +2 (switch) |
The symmetric cases apply for downvote. This fits neatly into a pure function:
function applyVote(post: Post, direction: 'up' | 'down'): Post {
const next = post.userVote === direction ? null : direction;
return { ...post, userVote: next };
}
The state update is then a single immutable map over the posts array:
setPosts(prev =>
prev.map(p => p.id === targetId ? applyVote(p, direction) : p)
);
Derived sort order
Never store a sorted copy in state — that creates two sources of truth. Instead, derive it:
const sortedPosts = useMemo(() => {
const score = (p: Post) =>
p.baseScore + (p.userVote === 'up' ? 1 : p.userVote === 'down' ? -1 : 0);
const comparator = (a: Post, b: Post) => {
const scoreDiff = score(b) - score(a);
if (scoreDiff !== 0) return scoreDiff;
return a.createdAt - b.createdAt; // older post wins ties — deterministic
};
const sticky = posts.filter(p => p.sticky).sort(comparator);
const normal = posts.filter(p => !p.sticky).sort(comparator);
return [...sticky, ...normal];
}, [posts]);
Using createdAt as a tie-breaker means the order is fully deterministic: the same state always produces the same list, so React's reconciler never has to move DOM nodes unnecessarily.
Sticky behaviour
Toggling sticky is a single field update — same pattern as the vote:
setPosts(prev =>
prev.map(p => p.id === targetId ? { ...p, sticky: !p.sticky } : p)
);
When a sticky post is voted on, useMemo re-runs, re-sorts the sticky group, and the post may change position within the sticky section. That is the correct and expected behaviour.
Accessibility
Two things matter most here:
Controls. Vote buttons need descriptive labels that include the current state:
<button
aria-label={`Upvote. Current score ${displayScore}`}
aria-pressed={post.userVote === 'up'}
onClick={() => handleVote(post.id, 'up')}
>
▲
</button>
Live score. Wrap the score in an aria-live region so screen readers announce changes without requiring a focus move:
<span aria-live="polite" aria-atomic="true">{displayScore}</span>
Focus on reorder. When a post moves in the list, the focused element may shift. A safe approach: capture document.activeElement's post id before the update, then in a useEffect after render, call .focus() on the element with that id. This keeps the user oriented.
Optimistic updates and rollback
For server persistence, apply the vote to local state immediately, then fire the request in the background:
async function handleVote(id: string, direction: 'up' | 'down') {
const previous = posts;
setPosts(prev => prev.map(p => p.id === id ? applyVote(p, direction) : p));
try {
await api.vote(id, direction);
} catch {
setPosts(previous); // full rollback
showErrorToast('Vote failed. Please try again.');
}
}
For rapid clicking, cancel in-flight requests with an AbortController and only apply the result of the last request. Alternatively, debounce the API call while keeping the UI snappy by accumulating local state changes in the meantime.
Common mistakes to avoid
- Storing derived sort order in state alongside the raw posts. One update then requires two state writes to stay consistent, and they can drift.
- Mutating the post object directly instead of spreading into a new object. React won't detect the change and won't re-render.
- Non-deterministic tie-breaking (e.g. relying on
Array.sort's natural stability without a secondary key). Different JS engines behave differently, and the list can flicker. - Forgetting the ±2 case when switching from downvote to upvote. A common off-by-one that produces wrong scores.
- No rollback on server error. Optimistic updates without rollback leave the UI in a permanently incorrect state if the network fails.