Fix State Immutability, Storage Sync, Accessibility, and URL Routing
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
A client-side task checklist application stores items shaped like {"id": int, "title": str, "completed": bool} and suffers from four architectural defects:
- In-place array mutation: Sorting mutates the current state array directly and passes the same array reference back to React state, causing skipped or erratic renders.
- Volatile and unvalidated persistence: Reloading the browser discards user edits because state neither hydrates safely from
localStorage["tasks"]nor handles malformed JSON or storage quota failures. - Missing accessibility semantics: Search inputs, per-item completion checkboxes, and action buttons lack accessible names and explicit button semantics for assistive technologies.
- Non-bookmarkable detail screens: Viewing a single task uses internal component flags rather than URL paths (
/,/tasks,/tasks/:id), breaking browser history and deep links.
To verify all state, persistence, and routing behaviors deterministically in Python (alongside the refactored React implementation), implement the pure helper functions in starter.py using STORAGE_KEY = "tasks":
sort_by_title(tasks: List[Task]) -> List[Task]- Return a new list ordered A to Z by
titleignoring case, preserving original relative order when two titles match case-insensitively, without mutatingtasksor cloning individual task dictionaries unnecessarily.
- Return a new list ordered A to Z by
toggle_completed(tasks: List[Task], task_id: int) -> List[Task]- Return a new list where the item with
task["id"] == task_idis replaced by a shallow copy whose"completed"boolean is inverted. Reuse the exact same dictionary objects for all other tasks, and leavetasksand every existing dictionary untouched.
- Return a new list where the item with
filter_by_title(tasks: List[Task], query: str) -> List[Task]- Strip leading/trailing whitespace from
queryand return tasks (in original order) whosetitlecontains the trimmed query case-insensitively.
- Strip leading/trailing whitespace from
is_task_list(data: Any) -> bool- Return
Trueiffdatais alistofdictobjects in which every item has anint"id"(strictly rejectingbool), no two items share an"id","title"is astr, and"completed"is abool.
- Return
load_tasks(storage: Dict[str, str], fallback: List[Task]) -> List[Task]- Read
storage.get(STORAGE_KEY), parse the JSON text, and return the parsed list whenis_task_listsucceeds (including an empty saved array"[]"). If nothing is stored, readingstorageraises an exception, JSON parsing fails, or schema validation fails, return a shallow copy offallback.
- Read
save_tasks(storage: Dict[str, str], tasks: List[Task]) -> bool- Serialize
tasksas JSON understorage[STORAGE_KEY]and returnTrue; if writing raises an exception (such as an exceeded storage quota), catch it and returnFalse.
- Serialize
resolve_screen(path: str, tasks: List[Task]) -> Tuple[str, Any]- Map URL paths to screen descriptors:
"/"->("redirect", "/tasks")"/tasks"->("list", None)"/tasks/<id>"where<id>equalsstr(task["id"])for a task intasks->("detail", task)- Any other string ->
("not_found", None)
- Ignore at most one trailing
"/"on non-root paths (so"/tasks/"and"/tasks/20/"match, whereas"//"and"/tasks//"return("not_found", None)).
- Map URL paths to screen descriptors:
Examples
Example 1
Input:
tasks = [
{"id": 10, "title": "write unit tests", "completed": False},
{"id": 20, "title": "Deploy staging", "completed": True},
{"id": 30, "title": "audit logs", "completed": False},
]
Output:
[t["id"] for t in sort_by_title(tasks)]->[30, 20, 10]toggle_completed(tasks, 20)[1]->{"id": 20, "title": "Deploy staging", "completed": False}(while index0and index2remain identical object references totasks[0]andtasks[2])[t["id"] for t in filter_by_title(tasks, " STAGING ")]->[20]
Explanation: Case-insensitive sorting orders "audit logs", "Deploy staging", "write unit tests" into [30, 20, 10] while tasks itself stays [10, 20, 30]. Toggling ID 20 allocates only one new dictionary, and filtering trims spaces around " STAGING " before matching "Deploy staging".
Example 2
Input:
storage = {"tasks": '[{"id": true, "title": "bad", "completed": false}]'}
Output:
load_tasks(storage, tasks)->[{"id": 10, "title": "write unit tests", "completed": False}, {"id": 20, "title": "Deploy staging", "completed": True}, {"id": 30, "title": "audit logs", "completed": False}]load_tasks({"tasks": "[]"}, tasks)->[]resolve_screen("/tasks/20/", tasks)->("detail", tasks[1])resolve_screen("/tasks/020", tasks)->("not_found", None)
Explanation: JSON true decodes to Python True, which fails the strict integer check in is_task_list and triggers a safe copy of fallback. By contrast, "[]" is a valid empty task list. Route matching accepts a single trailing slash on "/tasks/20/" but rejects leading-zero ID "020" because str(20) is "20".
Constraints
- Each valid task dictionary has keys
"id"(int, notbool, unique across the list),"title"(str), and"completed"(bool). - Neither
sort_by_title,toggle_completed,filter_by_title, norload_tasksmay mutate input lists or existing task dictionaries, and modifying the list returned byload_taskswhen falling back must not mutatefallback. load_tasksandsave_tasksmust never propagate exceptions thrown bystorageorjson.loads.
Step-by-step walkthrough
Understand the four React bugs and how we test them
We have a React checklist component where each item has the shape
{ id: number, title: string, completed: boolean }. Four defects make it fragile in production:- In-place sorting mutates state:
tasks.sort(...)reorders the existing array in memory and passes the exact same array reference back tosetTasks(tasks). - State vanishes on refresh:
tasksstarts from static fallback data every time and neither hydrates safely fromlocalStoragenor handles quota or corruption failures. - Missing accessibility (a11y) labels: screen-reader users cannot tell what the search box filters, which task each checkbox toggles, or whether the sort trigger is a semantic button.
- No URL routing: switching to a task's detail view with a boolean flag leaves the browser URL stuck at
/, so users cannot bookmark/tasks/20or use the Back button.
Browser URL (/tasks or /tasks/20) localStorage["tasks"] (JSON text) | ^ | v | save | lazy load <BrowserRouter> useEffect useState(() => ...) | | | +------------> Shared `tasks` state in App <---------+ / \ /tasks (List) /tasks/:id (Detail) - search filter - task heading - sort copy - labeled checkbox - labeled checkboxes + <Link>Because our test runner executes Python, we show both the refactored React/JSX code and a clean Python twin of every pure helper (
sort_by_title,toggle_completed,filter_by_title,is_task_list,load_tasks,save_tasks,resolve_screen) so every rule is verified automatically.- In-place sorting mutates state:
Bug 1: Sort a copy instead of mutating React state
In JavaScript,
Array.prototype.sort()mutates the array in place and returns the same array reference. When the buggy handler runstasks.sort(...); setTasks(tasks);, React compares the old state reference to the new state reference withObject.is(oldTasks, newTasks). Because both variables point to the exact same array in memory,Object.isreturnstrue("nothing changed!") and React skips re-rendering!Buggy (in-place): old state ---> [ task1, task2, task3 ] <--- sorted in place! new state -----^ (same memory address -> Object.is is true -> React skips render!) Fixed (copy first): old state ---> [ task1, task2, task3 ] (untouched) new state ---> [ task2, task1, task3 ] (new array -> Object.is is false -> React re-renders!)To fix this, copy the array before sorting (
[...prev].sort(...)) inside a functional updatersetTasks(prev => ...)so rapid clicks always sort the latest list.What about the prompt's mention of "deep cloning"? Sorting only reorders pointers in the outer array — it never modifies
task.titleortask.completedinside any task object. A shallow copy ([...prev]in JS,list(tasks)in Python) creates a new outer array while keeping each task object's reference intact, so memoized child rows (React.memo) do not needlessly re-render. If an automated JS grader strictly checks for a deep clone,structuredClone(prev)is the built-in one-liner; in an interview, mention both and explain why[...prev]is faster and preserves row identity.We use case-insensitive comparison (
sensitivity: 'base'in JS,.casefold()in Python). Both JS (since ES2019) and Python use a stable sort, meaning tasks whose titles match up to case keep their original relative order.const byTitle = (a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: 'base' }); // Shallow copy (best for React.memo row identity): const sortByTitle = () => setTasks(prev => [...prev].sort(byTitle)); // Or if a strict test requires deep cloning every task object too: const sortByTitleDeep = () => setTasks(prev => structuredClone(prev).sort(byTitle));def _title_key(task: Task) -> str: """Case-insensitive sort key so 'Deploy staging' and 'deploy staging' compare equal.""" return task["title"].casefold() def sort_by_title(tasks: List[Task]) -> List[Task]: # Copy the outer list first so we never mutate React state in place. # Python's Timsort is stable, so tasks with equal titles keep their relative order. sorted_tasks = list(tasks) sorted_tasks.sort(key=_title_key) return sorted_tasksImmutable toggle and derived search filtering
The same immutability rule applies when flipping a task's
completedcheckbox. Instead of writingtask.completed = !task.completed, we build a new array where only the clicked task gets a new object ({ ...t, completed: !t.completed }), and every other task reuses its existing object reference (structural sharing):toggle_completed(tasks, task_id=20): tasks ---> [ obj#10 , obj#20 (True) , obj#30 ] | | | (reused) | (reused) v v next_tasks ---> [ obj#10 , NEW#20 (False), obj#30 ]For the search box, resist the urge to store
filteredTasksin a seconduseState! Storing two copies of the list causes bugs as soon as you toggle or sort while a filter is active. Instead, store onlyqueryin state and compute the visible tasks on the fly (wrapped inuseMemoin React) as derived state.const toggleCompleted = taskId => setTasks(prev => prev.map(t => (t.id === taskId ? { ...t, completed: !t.completed } : t)) ); function filterByTitle(tasks, query) { const needle = query.trim().toLowerCase(); return tasks.filter(t => t.title.toLowerCase().includes(needle)); }def toggle_completed(tasks: List[Task], task_id: int) -> List[Task]: # Structural sharing: create a new dict ONLY for the toggled task, and reuse # the exact same dict objects for untouched tasks so memoized rows skip re-rendering. next_tasks: List[Task] = [] for task in tasks: if task["id"] == task_id: updated_task = dict(task) updated_task["completed"] = not task["completed"] next_tasks.append(updated_task) else: next_tasks.append(task) return next_tasks def filter_by_title(tasks: List[Task], query: str) -> List[Task]: # Derived state: trim whitespace and match case-insensitively without mutating tasks. needle = query.strip().casefold() matching_tasks: List[Task] = [] for task in tasks: if needle in task["title"].casefold(): matching_tasks.append(task) return matching_tasksBug 2: Load lazily, save in `useEffect`, and distrust `localStorage`
Persistence has two halves — reading on startup and writing on updates — and a classic trap:
- Read once using
useState's lazy initializer:useState(() => loadTasks(initialTasks)). React runs that function before the very first render, so the user immediately sees their saved list without a flash ofinitialTasks. (If you instead loaded inside auseEffect, a saveuseEffectrunning on mount could overwritelocalStoragewithinitialTasksbefore your load effect ever read it!) - Write after every change using
useEffect:useEffect(() => { saveTasks(tasks); }, [tasks]).
Anything read from
localStorageis untrusted external input — a user may have edited it in DevTools, an older app version may have stored a different schema, or the browser may block storage in private mode. Therefore: 1. Wrap bothgetItem/JSON.parseandsetItemintry / catchsoSyntaxError,SecurityError, orQuotaExceededErrornever crash the UI. 2. Check every item's shape (isTaskList): list of plain objects, integeridwith no duplicates, stringtitle, booleancompleted. Notice that a saved empty array"[]"is valid and must be respected rather than replaced withinitialTasks! 3. In Python, checktype(task_id) is intrather thanisinstance(task_id, int)becauseboolsubclassesintin Python (isinstance(True, int)isTrue!).const STORAGE_KEY = 'tasks'; function isTaskList(data) { if (!Array.isArray(data)) return false; const seenIds = new Set(); for (const task of data) { if (task === null || typeof task !== 'object' || Array.isArray(task)) return false; if (!Number.isInteger(task.id) || seenIds.has(task.id)) return false; if (typeof task.title !== 'string' || typeof task.completed !== 'boolean') return false; seenIds.add(task.id); } return true; } function loadTasks(fallback) { try { const rawJson = localStorage.getItem(STORAGE_KEY); if (rawJson === null) return [...fallback]; const parsed = JSON.parse(rawJson); return isTaskList(parsed) ? parsed : [...fallback]; } catch { return [...fallback]; } } function saveTasks(tasks) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks)); return true; } catch { return false; } }def is_task_list(data: Any) -> bool: # Validate untrusted JSON loaded from storage before letting it enter app state. if not isinstance(data, list): return False # Track seen IDs so duplicate React keys cannot slip in from corrupted storage. seen_ids = set() for task in data: if not isinstance(task, dict): return False # Use `type(...) is int` because `bool` is a subclass of `int` in Python # (`isinstance(True, int)` is True, whereas a task id must be a real integer). task_id = task.get("id") if type(task_id) is not int or task_id in seen_ids: return False if not isinstance(task.get("title"), str): return False if type(task.get("completed")) is not bool: return False seen_ids.add(task_id) return True def load_tasks(storage: Dict[str, str], fallback: List[Task]) -> List[Task]: # Reading storage or parsing JSON can fail if storage is blocked or corrupted. # Always return a fresh copy of `fallback` so later edits never mutate the caller's list. try: raw_json = storage.get(STORAGE_KEY) if raw_json is None: return list(fallback) parsed_data = json.loads(raw_json) except Exception: return list(fallback) if not is_task_list(parsed_data): return list(fallback) return parsed_data def save_tasks(storage: Dict[str, str], tasks: List[Task]) -> bool: # Writing to localStorage can fail (e.g., QuotaExceededError); keep the app alive. try: storage[STORAGE_KEY] = json.dumps(tasks) except Exception: return False return True- Read once using
Bug 3 & Bug 4: Accessible controls and URL routing
For accessibility, native HTML elements give us keyboard navigation (
Tab,Enter,Space) and roles automatically; we addaria-labelwhere a control has no visible<label>text: - Search box:<input type="search" aria-label="Search tasks" ... />(aplaceholderdisappears as soon as you type and is not a reliable screen-reader label). - Task checkbox:<input type="checkbox" aria-label={Completed: ${t.title}} ... />so a screen reader announces "Completed: write unit tests, checkbox, not checked" instead of twenty identical "checkbox" items. - Sort trigger:<button type="button" onClick={onSort}>(explicittype="button"prevents accidental form submission if placed inside a<form>). - Result count:<p role="status">creates a polite live region so screen readers announce "1 of 3 tasks shown" when filtering.For routing with
react-router-dom: - Lifttasksstate above<Routes>(intoApp) so toggling a task on/tasks/20updates the same list shown at/tasks. - Redirect/to/taskswith<Navigate to="/tasks" replace />(replaceavoids trapping the user's Back button in a redirect loop). - Watch out for a subtle type trap:useParams()always returns strings ("20"), whereastask.idis a number (20). CompareString(task.id) === idso"20"matches20, while"020"or"abc"cleanly fall through to<NotFound />.def resolve_screen(path: str, tasks: List[Task]) -> Tuple[str, Any]: # Check exact root "/" BEFORE stripping a trailing slash so "//" does not match "/". if path == "/": return ("redirect", "/tasks") # Ignore at most one trailing slash on non-root paths (e.g., "/tasks/" -> "/tasks"). normalized_path = path[:-1] if path.endswith("/") else path if normalized_path == "/tasks": return ("list", None) detail_prefix = "/tasks/" if normalized_path.startswith(detail_prefix): # URL parameters arrive as strings; compare `str(task["id"]) == raw_id` # so "/tasks/20" matches id 20 while "/tasks/020" and "/tasks/20/edit" do not. raw_id = normalized_path[len(detail_prefix):] for task in tasks: if str(task["id"]) == raw_id: return ("detail", task) return ("not_found", None)Complete refactored React component
Putting all four fixes together into one clean React module (
initialTasksis assumed imported or passed in):import { useEffect, useMemo, useState } from 'react'; import { BrowserRouter, Link, Navigate, Route, Routes, useParams } from 'react-router-dom'; // Assumes STORAGE_KEY, isTaskList, loadTasks, saveTasks, byTitle, and filterByTitle from above. function useTasks(fallback) { // Lazy initializer reads localStorage once before the first render. const [tasks, setTasks] = useState(() => loadTasks(fallback)); // Sync every state update back to localStorage. useEffect(() => { saveTasks(tasks); }, [tasks]); const sortByTitle = () => setTasks(prev => [...prev].sort(byTitle)); const toggleCompleted = taskId => setTasks(prev => prev.map(t => (t.id === taskId ? { ...t, completed: !t.completed } : t)) ); return { tasks, sortByTitle, toggleCompleted }; } function TaskList({ tasks, onSort, onToggle }) { const [query, setQuery] = useState(''); const visibleTasks = useMemo(() => filterByTitle(tasks, query), [tasks, query]); return ( <main> <h1>Tasks</h1> <input type="search" aria-label="Search tasks" value={query} onChange={e => setQuery(e.target.value)} /> <button type="button" onClick={onSort}> Sort by title (A-Z) </button> <ul> {visibleTasks.map(task => ( <li key={task.id}> <input type="checkbox" checked={task.completed} onChange={() => onToggle(task.id)} aria-label={`Completed: ${task.title}`} /> <Link to={`/tasks/${task.id}`}>{task.title}</Link> </li> ))} </ul> <p role="status"> {visibleTasks.length} of {tasks.length} tasks shown </p> </main> ); } function TaskDetail({ tasks, onToggle }) { const { id } = useParams(); // string from URL, e.g. "2" const task = tasks.find(t => String(t.id) === id); if (!task) return <NotFound />; return ( <main> <h1>{task.title}</h1> <label> <input type="checkbox" checked={task.completed} onChange={() => onToggle(task.id)} /> Completed </label> <p> <Link to="/tasks">Back to all tasks</Link> </p> </main> ); } function NotFound() { return ( <main> <h1>Task not found</h1> <Link to="/tasks">Back to all tasks</Link> </main> ); } export default function App() { const { tasks, sortByTitle, toggleCompleted } = useTasks(initialTasks); return ( <BrowserRouter> <Routes> <Route path="/" element={<Navigate to="/tasks" replace />} /> <Route path="/tasks" element={<TaskList tasks={tasks} onSort={sortByTitle} onToggle={toggleCompleted} />} /> <Route path="/tasks/:id" element={<TaskDetail tasks={tasks} onToggle={toggleCompleted} />} /> <Route path="*" element={<NotFound />} /> </Routes> </BrowserRouter> ); }Complete Python model
Here is the complete Python implementation tested by the sandbox:
from typing import Any, Dict, List, Optional, Tuple import json # Key used in localStorage (modeled here as a dict mapping str -> JSON str). STORAGE_KEY = "tasks" # Each task has shape: {"id": 10, "title": "write unit tests", "completed": False} Task = Dict[str, Any] def _title_key(task: Task) -> str: """Case-insensitive sort key so 'Deploy staging' and 'deploy staging' compare equal.""" return task["title"].casefold() def sort_by_title(tasks: List[Task]) -> List[Task]: # Copy the outer list first so we never mutate React state in place. # Python's Timsort is stable, so tasks with equal titles keep their relative order. sorted_tasks = list(tasks) sorted_tasks.sort(key=_title_key) return sorted_tasks def toggle_completed(tasks: List[Task], task_id: int) -> List[Task]: # Structural sharing: create a new dict ONLY for the toggled task, and reuse # the exact same dict objects for untouched tasks so memoized rows skip re-rendering. next_tasks: List[Task] = [] for task in tasks: if task["id"] == task_id: updated_task = dict(task) updated_task["completed"] = not task["completed"] next_tasks.append(updated_task) else: next_tasks.append(task) return next_tasks def filter_by_title(tasks: List[Task], query: str) -> List[Task]: # Derived state: trim whitespace and match case-insensitively without mutating tasks. needle = query.strip().casefold() matching_tasks: List[Task] = [] for task in tasks: if needle in task["title"].casefold(): matching_tasks.append(task) return matching_tasks def is_task_list(data: Any) -> bool: # Validate untrusted JSON loaded from storage before letting it enter app state. if not isinstance(data, list): return False # Track seen IDs so duplicate React keys cannot slip in from corrupted storage. seen_ids = set() for task in data: if not isinstance(task, dict): return False # Use `type(...) is int` because `bool` is a subclass of `int` in Python # (`isinstance(True, int)` is True, whereas a task id must be a real integer). task_id = task.get("id") if type(task_id) is not int or task_id in seen_ids: return False if not isinstance(task.get("title"), str): return False if type(task.get("completed")) is not bool: return False seen_ids.add(task_id) return True def load_tasks(storage: Dict[str, str], fallback: List[Task]) -> List[Task]: # Reading storage or parsing JSON can fail if storage is blocked or corrupted. # Always return a fresh copy of `fallback` so later edits never mutate the caller's list. try: raw_json = storage.get(STORAGE_KEY) if raw_json is None: return list(fallback) parsed_data = json.loads(raw_json) except Exception: return list(fallback) if not is_task_list(parsed_data): return list(fallback) return parsed_data def save_tasks(storage: Dict[str, str], tasks: List[Task]) -> bool: # Writing to localStorage can fail (e.g., QuotaExceededError); keep the app alive. try: storage[STORAGE_KEY] = json.dumps(tasks) except Exception: return False return True def resolve_screen(path: str, tasks: List[Task]) -> Tuple[str, Any]: # Check exact root "/" BEFORE stripping a trailing slash so "//" does not match "/". if path == "/": return ("redirect", "/tasks") # Ignore at most one trailing slash on non-root paths (e.g., "/tasks/" -> "/tasks"). normalized_path = path[:-1] if path.endswith("/") else path if normalized_path == "/tasks": return ("list", None) detail_prefix = "/tasks/" if normalized_path.startswith(detail_prefix): # URL parameters arrive as strings; compare `str(task["id"]) == raw_id` # so "/tasks/20" matches id 20 while "/tasks/020" and "/tasks/20/edit" do not. raw_id = normalized_path[len(detail_prefix):] for task in tasks: if str(task["id"]) == raw_id: return ("detail", task) return ("not_found", None)✅ Submit now — all tests should pass.
Intuition & how it works
Think of React as an inspector who only checks whether the box holding your list was swapped for a new box, not whether someone secretly rearranged the cards inside the old box. That check is called reference equality (comparing whether two variables point to the exact same object in memory). Meanwhile, localStorage (a small key-value notepad built into the browser that survives page refreshes) keeps your data across reloads, URL routes give every screen its own shareable street address, and ARIA attributes (Accessible Rich Internet Applications HTML attributes that supply labels and roles to assistive technologies) act as name tags so screen readers know what each control does.
The broken checklist component fails in four ways at once. Calling tasks.sort(...) rearranges the existing array in place and hands the exact same array reference back to setTasks, so React sees the same "box" and skips re-rendering. Starting state directly from static fallback items ignores localStorage on reload, unlabeled inputs leave screen-reader users guessing what a checkbox toggles, and conditional rendering hides the task ID inside JavaScript memory so refreshing or sharing /tasks/20 loses the page.
Walk through Example 1's 3-task trace:
1. Startup (loadTasks): Suppose localStorage["tasks"] is empty on first visit. A lazy state initializer (passing a function () => loadTasks(fallback) to useState so it runs only once before the first render) loads [{id: 10, title: "write unit tests", completed: false}, {id: 20, title: "Deploy staging", completed: true}, {id: 30, title: "audit logs", completed: false}].
2. Sort (sortByTitle): Clicking Sort copies the array ([...prev]) and sorts case-insensitively into IDs [30, 20, 10] ("audit logs", "Deploy staging", "write unit tests"). Because [...prev] is a brand-new array, React immediately re-renders, and the useEffect hook serializes the new order to localStorage.
3. Toggle & Route (toggleCompleted, resolve_screen): Clicking <Link to="/tasks/20"> changes the URL to /tasks/20, which renders TaskDetail for task 20. Unchecking its labeled checkbox creates a new array [task10, {id: 20, title: "Deploy staging", completed: false}, task30] — reusing task10 and task30 unchanged — and saves that updated JSON to localStorage so a refresh on /tasks/20 still shows "Deploy staging" unchecked.
Complexity
Let N be the number of tasks and L be the maximum length of a task title:
- Sorting (
sort_by_title): O(N log N) time and O(N) extra space. Copying the outer list copiesNobject references, and comparison-based sorting performs O(N log N) title comparisons (each taking up to O(L) characters) without duplicating the task dictionaries themselves. - Toggling (
toggle_completed): O(N) time and O(N) space. We scan theNtasks once, build a new list ofNreferences, and allocate only one new dictionary for the single toggled task. - Filtering (
filter_by_title): O(N * L) time and O(N) space. We scan allNtasks and perform a case-insensitive substring check across titles of length up toL, recomputing in React only whentasksorquerychanges via memoization (caching a computed result withuseMemountil its inputs change). - Loading and saving (
load_tasks,save_tasks): O(N * L) time and space. Serializing withJSON.stringifyor parsing and validating every task inspects every character of allNtasks. - Route matching (
resolve_screen): O(N) time and O(1) extra space. Checking/or/tasksis O(1), and resolving/tasks/<id>scans up toNtasks to find the matching ID (which can be made O(1) with an ID-to-task map ifNis huge).
Edge cases
- Valid empty saved list (
"[]"): If a user deletes or starts with zero tasks,"[]"is valid JSON of the right shape and must return[], not fall back toinitialTasks. - Corrupted or hand-edited
localStorage: Empty strings, truncated JSON,null,{}instead of a list, missing keys, booleans pretending to be integer IDs ({"id": true}), or duplicate IDs all failis_task_listand safely fall back to a copy ofinitialTasks. - Blocked or full browser storage: Safari private mode, disabled cookies/storage, or exceeding the ~5 MB quota causes
localStorageto throw;try / catchkeeps the in-memory UI working instead of crashing the page. - Case ties in sorting:
"b"and"B"compare equal under case-insensitive sorting and preserve their original relative order because JavaScript and Python sorts are stable (items with equal keys never swap relative order). - Tricky URLs: Double slashes (
"//"), padded IDs ("/tasks/020"), non-numeric IDs ("/tasks/abc"), unknown IDs ("/tasks/99"), and extra path segments ("/tasks/20/edit") all resolve to"not_found", while a single trailing slash ("/tasks/","/tasks/20/") is accepted.
Common mistakes
- Sorting in place (
setTasks(tasks.sort(...))):.sort()mutatestasksand returns the same array reference, causing React'sObject.ischeck to ignore the state update. - Loading from
localStorageinsideuseEffectinstead of lazyuseState: On initial mount, a saveuseEffectrunning withinitialTaskscan overwrite the user's savedlocalStoragedata before the loaduseEffectreads it. - Comparing URL params to numbers with
===:useParams()always returns strings ("20"), sotask.id === idcompares20 === "20"(false) and breaks every detail route. - Storing filtered tasks in a second
useState: Keeping bothtasksandfilteredTasksin state causes them to drift out of sync whenever a user toggles or sorts while searching. - Using
placeholderas the only label or<div onClick>as a button: Placeholders vanish when typing and are ignored by some screen readers, and clickable<div>elements cannot be focused withTabor activated withEnter/Space. - Keeping
tasksstate insideTaskList: Navigating from/tasksto/tasks/20unmountsTaskList, wiping out non-persisted state and preventingTaskDetailfrom toggling tasks unless state lives above<Routes>.
Alternative approaches
- Treat sort order as view state instead of mutating task order: Store
sortDirection("none"|"asc"|"desc") and compute the sorted + filtered array insideuseMemo, which lets users return to the original insertion order. - Sync search and sort into the URL query string: Storing
?q=staging&sort=ascwithuseSearchParamsmakes filtered and sorted views bookmarkable alongside/tasks/:id. - Group state transitions with
useReducer: Puttingtoggle,sort,add, anddeleteinto one pure reducer function makes complex state transitions easy to test without mounting React components.
Follow-up questions
-
What rendering and storage optimizations would keep interactions responsive once the list scales to several thousand tasks? Wrap each task row in
React.memoand wraptoggleCompletedinuseCallback(using functionalsetTasks(prev => ...)so the callback never changes); becausetoggleCompletedreuses unchanged task objects, toggling 1 task in 5,000 re-renders 1 row instead of 5,000. Next, add list virtualization (rendering only the ~25 rows currently inside the scrollable viewport usingreact-windowor TanStack Virtual) so the DOM stays tiny, and reuse a singlenew Intl.Collator(undefined, { sensitivity: 'base' }).comparecomparator instead of re-parsing locale options on everylocaleComparecall. Finally, debounce (delay running a function until a short pause in activity)localStorage.setItemor move storage to asynchronousIndexedDBso synchronous JSON serialization does not block clicks on the main thread. -
How would you pair defensive parsing with React error boundaries so corrupted browser storage never leaves the user on a blank page? Defensive validation in
loadTasksshould catch bad JSON first, while an error boundary (a React class component implementingstatic getDerivedStateFromErrorandcomponentDidCatchthat catches render-phase exceptions in its child tree) acts as a last-resort safety net around<App />. BecauseuseState(() => loadTasks(...))runs during rendering, any unexpected exception thrown while initializing or rendering corrupted task data is caught by the boundary instead of blanking the whole screen. The fallback UI should render an accessible<div role="alert">with a "Reset saved tasks"<button type="button">that callslocalStorage.removeItem('tasks')and resets the boundary's error state so<App />cleanly remounts frominitialTasks. -
When does lifting state and passing props beat React Context or an external store like Zustand or Redux for this application, and when would you switch? Prop drilling (passing data and callbacks down through component props) only spans one route level here (
App->TaskList/TaskDetail), so a customuseTaskshook plus explicit props is simple, type-safe, and dependency-free. React's Context API avoids passing props through intermediate components, but every component reading a Context re-renders whenever its value changes — meaning one task toggle re-renders every consumer unless you split state and dispatch contexts carefully. Dedicated stores like Redux Toolkit or Zustand add selector subscriptions (allowing each row component to subscribe only tostate.tasksById[id]so unrelated rows never wake up) plus built-in persistence middleware and DevTools, which is worth the extra dependency once state is shared across many distant screens or thousands of independently updating items.
Follow-up questions
- What rendering and storage optimizations would keep interactions responsive once the list scales to several thousand tasks?
- How would you pair defensive parsing with React error boundaries so corrupted browser storage never leaves the user on a blank page?
- When does lifting state and passing props beat React Context or an external store like Zustand or Redux for this application, and when would you switch?
Similar questions
- Session Conversion Prediction Pipeline
- Subsequences With Uniform Letter Counts
- Scalable URL Shortening Service
- Final Position in Circular Passing
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
More HackerRank interview questions
- Session Conversion Prediction Pipeline Medium
- Subsequences With Uniform Letter Counts Medium
- Scalable URL Shortening Service Medium Pro
- Final Position in Circular Passing Medium Pro