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:

  1. 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.
  2. 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.
  3. Missing accessibility semantics: Search inputs, per-item completion checkboxes, and action buttons lack accessible names and explicit button semantics for assistive technologies.
  4. 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 title ignoring case, preserving original relative order when two titles match case-insensitively, without mutating tasks or cloning individual task dictionaries unnecessarily.
  • toggle_completed(tasks: List[Task], task_id: int) -> List[Task]
    • Return a new list where the item with task["id"] == task_id is replaced by a shallow copy whose "completed" boolean is inverted. Reuse the exact same dictionary objects for all other tasks, and leave tasks and every existing dictionary untouched.
  • filter_by_title(tasks: List[Task], query: str) -> List[Task]
    • Strip leading/trailing whitespace from query and return tasks (in original order) whose title contains the trimmed query case-insensitively.
  • is_task_list(data: Any) -> bool
    • Return True iff data is a list of dict objects in which every item has an int "id" (strictly rejecting bool), no two items share an "id", "title" is a str, and "completed" is a bool.
  • 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 when is_task_list succeeds (including an empty saved array "[]"). If nothing is stored, reading storage raises an exception, JSON parsing fails, or schema validation fails, return a shallow copy of fallback.
  • save_tasks(storage: Dict[str, str], tasks: List[Task]) -> bool
    • Serialize tasks as JSON under storage[STORAGE_KEY] and return True; if writing raises an exception (such as an exceeded storage quota), catch it and return False.
  • 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> equals str(task["id"]) for a task in tasks -> ("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)).

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 index 0 and index 2 remain identical object references to tasks[0] and tasks[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, not bool, unique across the list), "title" (str), and "completed" (bool).
  • Neither sort_by_title, toggle_completed, filter_by_title, nor load_tasks may mutate input lists or existing task dictionaries, and modifying the list returned by load_tasks when falling back must not mutate fallback.
  • load_tasks and save_tasks must never propagate exceptions thrown by storage or json.loads.

Step-by-step walkthrough

  1. 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:

    1. In-place sorting mutates state: tasks.sort(...) reorders the existing array in memory and passes the exact same array reference back to setTasks(tasks).
    2. State vanishes on refresh: tasks starts from static fallback data every time and neither hydrates safely from localStorage nor handles quota or corruption failures.
    3. 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.
    4. 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/20 or 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.

  2. 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 runs tasks.sort(...); setTasks(tasks);, React compares the old state reference to the new state reference with Object.is(oldTasks, newTasks). Because both variables point to the exact same array in memory, Object.is returns true ("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 updater setTasks(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.title or task.completed inside 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_tasks
    
  3. Immutable toggle and derived search filtering

    The same immutability rule applies when flipping a task's completed checkbox. Instead of writing task.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 filteredTasks in a second useState! Storing two copies of the list causes bugs as soon as you toggle or sort while a filter is active. Instead, store only query in state and compute the visible tasks on the fly (wrapped in useMemo in 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_tasks
    
  4. Bug 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 of initialTasks. (If you instead loaded inside a useEffect, a save useEffect running on mount could overwrite localStorage with initialTasks before your load effect ever read it!)
    • Write after every change using useEffect: useEffect(() => { saveTasks(tasks); }, [tasks]).

    Anything read from localStorage is 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 both getItem/JSON.parse and setItem in try / catch so SyntaxError, SecurityError, or QuotaExceededError never crash the UI. 2. Check every item's shape (isTaskList): list of plain objects, integer id with no duplicates, string title, boolean completed. Notice that a saved empty array "[]" is valid and must be respected rather than replaced with initialTasks! 3. In Python, check type(task_id) is int rather than isinstance(task_id, int) because bool subclasses int in Python (isinstance(True, int) is True!).

    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
    
  5. 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 add aria-label where a control has no visible <label> text: - Search box: <input type="search" aria-label="Search tasks" ... /> (a placeholder disappears 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}> (explicit type="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: - Lift tasks state above <Routes> (into App) so toggling a task on /tasks/20 updates the same list shown at /tasks. - Redirect / to /tasks with <Navigate to="/tasks" replace /> (replace avoids trapping the user's Back button in a redirect loop). - Watch out for a subtle type trap: useParams() always returns strings ("20"), whereas task.id is a number (20). Compare String(task.id) === id so "20" matches 20, 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)
    
  6. Complete refactored React component

    Putting all four fixes together into one clean React module (initialTasks is 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>
      );
    }
    
  7. 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 copies N object 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 the N tasks once, build a new list of N references, 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 all N tasks and perform a case-insensitive substring check across titles of length up to L, recomputing in React only when tasks or query changes via memoization (caching a computed result with useMemo until its inputs change).
  • Loading and saving (load_tasks, save_tasks): O(N * L) time and space. Serializing with JSON.stringify or parsing and validating every task inspects every character of all N tasks.
  • Route matching (resolve_screen): O(N) time and O(1) extra space. Checking / or /tasks is O(1), and resolving /tasks/<id> scans up to N tasks to find the matching ID (which can be made O(1) with an ID-to-task map if N is 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 to initialTasks.
  • 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 fail is_task_list and safely fall back to a copy of initialTasks.
  • Blocked or full browser storage: Safari private mode, disabled cookies/storage, or exceeding the ~5 MB quota causes localStorage to throw; try / catch keeps 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() mutates tasks and returns the same array reference, causing React's Object.is check to ignore the state update.
  • Loading from localStorage inside useEffect instead of lazy useState: On initial mount, a save useEffect running with initialTasks can overwrite the user's saved localStorage data before the load useEffect reads it.
  • Comparing URL params to numbers with ===: useParams() always returns strings ("20"), so task.id === id compares 20 === "20" (false) and breaks every detail route.
  • Storing filtered tasks in a second useState: Keeping both tasks and filteredTasks in state causes them to drift out of sync whenever a user toggles or sorts while searching.
  • Using placeholder as 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 with Tab or activated with Enter/Space.
  • Keeping tasks state inside TaskList: Navigating from /tasks to /tasks/20 unmounts TaskList, wiping out non-persisted state and preventing TaskDetail from 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 inside useMemo, which lets users return to the original insertion order.
  • Sync search and sort into the URL query string: Storing ?q=staging&sort=asc with useSearchParams makes filtered and sorted views bookmarkable alongside /tasks/:id.
  • Group state transitions with useReducer: Putting toggle, sort, add, and delete into 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.memo and wrap toggleCompleted in useCallback (using functional setTasks(prev => ...) so the callback never changes); because toggleCompleted reuses 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 using react-window or TanStack Virtual) so the DOM stays tiny, and reuse a single new Intl.Collator(undefined, { sensitivity: 'base' }).compare comparator instead of re-parsing locale options on every localeCompare call. Finally, debounce (delay running a function until a short pause in activity) localStorage.setItem or move storage to asynchronous IndexedDB so 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 loadTasks should catch bad JSON first, while an error boundary (a React class component implementing static getDerivedStateFromError and componentDidCatch that catches render-phase exceptions in its child tree) acts as a last-resort safety net around <App />. Because useState(() => 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 calls localStorage.removeItem('tasks') and resets the boundary's error state so <App /> cleanly remounts from initialTasks.

  • 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 custom useTasks hook 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 to state.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

Similar questions

More HackerRank interview questions

All 5 HackerRank questions →