KatInterview

Fixing State Mutations, Storage, and Routes in React

BehavioralModel answer
MediumModel answerBehavioralreactstate-managementaccessibility

Last updated

Repair a task list component suffering from direct state mutation, missing localStorage sync, inaccessible markup, and hardcoded navigation.

Problem Statement

You inherit a React task-list component with multiple defects that prevent it from working correctly in production. Your job is to identify and resolve each issue while applying modern React patterns.

Current Issues

The component exhibits four critical problems:

  1. Direct state mutation during sort: The sort handler modifies the tasks array in place and then calls setTasks with the same reference, preventing React from detecting the change.

  2. No persistence: All task data disappears when the page reloads. Changes should be saved to and restored from localStorage.

  3. Missing accessibility semantics: Filter controls and checkboxes lack proper labels, making the interface unusable with screen readers.

  4. URL-less navigation: The detail view is shown/hidden with conditional rendering rather than proper routing, so users cannot bookmark or share links to individual tasks.

Existing Code Snippet

function TaskManager() {
  const [tasks, setTasks] = useState(initialTasks);

  const handleSort = () => {
    // Problem: mutating state directly
    tasks.sort((a, b) => a.title.localeCompare(b.title));
    setTasks(tasks);
  };

  return (
    <div>
      <ul>
        {tasks.map(t => <li key={t.id}>{t.title}</li>)}
      </ul>
      <button onClick={handleSort}>Sort</button>
    </div>
  );
}

Your Task

Refactor this component to meet the following requirements:

  • Immutability: Create a new array when sorting instead of mutating the existing one.
  • Persistence: Load the task list from localStorage on mount and save it back whenever the list changes.
  • Accessibility: Add appropriate labels and ARIA attributes so all interactive elements have accessible names.
  • Routing: Use react-router-dom to implement /tasks (list view) and /tasks/:id (detail view) as separate routes.

Assumptions

  • Each task is an object with shape { id: number, title: string, completed: boolean }.
  • initialTasks is a default array used when storage is empty or invalid.
  • You may use React hooks and react-router-dom v6.

Hints

Hint 1

React's state comparison uses Object.is—mutating an array in place won't trigger a re-render

Hint 2

localStorage operations can throw exceptions in private browsing mode or when quota is exceeded

Hint 3

The lazy initializer form of useState runs only once, preventing flashes of default data

Hint 4

useParams returns strings, not numbers, so you'll need to convert the id when looking up a task