Fixing State Mutations, Storage, and Routes in React
BehavioralModel answerLast 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:
-
Direct state mutation during sort: The sort handler modifies the tasks array in place and then calls
setTaskswith the same reference, preventing React from detecting the change. -
No persistence: All task data disappears when the page reloads. Changes should be saved to and restored from
localStorage. -
Missing accessibility semantics: Filter controls and checkboxes lack proper labels, making the interface unusable with screen readers.
-
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
localStorageon 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-domto 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 }. initialTasksis a default array used when storage is empty or invalid.- You may use React hooks and
react-router-domv6.
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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Fixing State Mutations, Storage, and Routes in React
Approach
Each bug stems from a misunderstanding of React fundamentals:
1. State Mutation During Sort
React relies on reference equality to detect state changes. When you call tasks.sort(...), you reorder the array in place and then pass the same reference back to setTasks. React sees no difference and may skip re-rendering.
Fix: Create a shallow copy before sorting:
const handleSort = () => {
setTasks(prev => [...prev].sort((a, b) =>
a.title.localeCompare(b.title)
));
};
Using the functional updater form (prev => ...) also prevents stale closures when multiple updates occur in quick succession.
You only need a shallow copy here—sort reorders references without touching the task objects themselves. Deep cloning with structuredClone would work but wastes memory and breaks memoization by creating new object identities unnecessarily.
2. Persistence with localStorage
To restore data on mount and save changes automatically:
- Load once: Use a lazy initializer with
useStateto read from storage during the first render only. - Save on every change: Use
useEffectwith[tasks]as the dependency to write back whenever the list updates.
function loadFromStorage(fallback) {
try {
const raw = localStorage.getItem('tasks');
if (!raw) return fallback;
const parsed = JSON.parse(raw);
// Validate shape to avoid runtime errors
return Array.isArray(parsed) && parsed.every(isValidTask)
? parsed
: fallback;
} catch {
return fallback;
}
}
const [tasks, setTasks] = useState(() => loadFromStorage(initialTasks));
useEffect(() => {
try {
localStorage.setItem('tasks', JSON.stringify(tasks));
} catch {
// Storage unavailable or full—continue working in memory
}
}, [tasks]);
The lazy initializer prevents a flash where initialTasks appears briefly before the stored data loads. The validation check ensures corrupt or mismatched JSON doesn't crash the app.
3. Accessibility
Every interactive control needs an accessible name:
- Text inputs: Use a
<label>element oraria-label. - Checkboxes: Pair with a
<label>that includes meaningful context. - Buttons: Use semantic
<button>elements, not clickable<div>s withrole="button".
<label htmlFor="search">Filter tasks</label>
<input id="search" type="text" value={query} onChange={e => setQuery(e.target.value)} />
<input
type="checkbox"
id={`task-${t.id}`}
checked={t.completed}
onChange={() => onToggle(t.id)}
/>
<label htmlFor={`task-${t.id}`}>Mark "{t.title}" complete</label>
Avoid redundant ARIA—role="button" on a real <button> is noise.
4. Routing with react-router-dom
Replace conditional rendering with declarative routes:
<BrowserRouter>
<Routes>
<Route path="/tasks" element={<TaskList ... />} />
<Route path="/tasks/:id" element={<TaskDetail ... />} />
<Route path="/" element={<Navigate to="/tasks" replace />} />
</Routes>
</BrowserRouter>
In the detail component, extract the id from the URL:
const { id } = useParams();
const task = tasks.find(t => t.id === Number(id));
Critical gotcha: useParams() returns strings. Comparing t.id === id will silently fail because 3 !== "3". Always parse numeric params.
Use <Link to={/tasks/${t.id}}> for navigation so the browser's back button works and users can bookmark individual tasks.
Complexity
- Sorting: O(n log n) time, O(n) space for the shallow copy.
- Filtering: O(n) per render. Wrap in
useMemo([tasks, query])to recompute only when inputs change. - Persistence: O(n) to serialize the array on each update.
- Detail lookup: O(n) with
find. If lookups become frequent, maintain aMap<id, task>for O(1) access.
Edge Cases and Trade-offs
- Storage unavailable: Private browsing, quota exceeded, or SSR environments may lack
localStorage. Wrap all operations intry/catch. - Corrupt data: Parse failures or wrong schema should fall back to defaults rather than crash.
- Unknown route:
/tasks/999or/tasks/abcshould render a "not found" message. - Empty filter results: Show a helpful message in a live region so screen readers announce the change.
- Key prop: Use
key={t.id}instead of array index. Index keys break checkbox state after sorting or filtering.
Complete Implementation
import { useEffect, useMemo, useState } from 'react';
import { BrowserRouter, Routes, Route, Navigate, Link, useParams } from 'react-router-dom';
const STORAGE_KEY = 'tasks';
const isValidTask = (t) =>
t && typeof t.id === 'number' &&
typeof t.title === 'string' &&
typeof t.completed === 'boolean';
function loadFromStorage(fallback) {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return fallback;
const parsed = JSON.parse(raw);
return Array.isArray(parsed) && parsed.every(isValidTask) ? parsed : fallback;
} catch {
return fallback;
}
}
export default function App() {
const [tasks, setTasks] = useState(() => loadFromStorage(initialTasks));
useEffect(() => {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
} catch {
// Continue in memory if storage fails
}
}, [tasks]);
const sortByTitle = () =>
setTasks(prev =>
[...prev].sort((a, b) => a.title.localeCompare(b.title))
);
const toggleTask = (id) =>
setTasks(prev =>
prev.map(t => (t.id === id ? { ...t, completed: !t.completed } : t))
);
return (
<BrowserRouter>
<Routes>
<Route path="/tasks" element={
<TaskList tasks={tasks} onSort={sortByTitle} onToggle={toggleTask} />
} />
<Route path="/tasks/:id" element={
<TaskDetail tasks={tasks} onToggle={toggleTask} />
} />
<Route path="/" element={<Navigate to="/tasks" replace />} />
</Routes>
</BrowserRouter>
);
}
function TaskList({ tasks, onSort, onToggle }) {
const [query, setQuery] = useState('');
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
return q ? tasks.filter(t => t.title.toLowerCase().includes(q)) : tasks;
}, [tasks, query]);
return (
<div>
<h1>Tasks</h1>
<label htmlFor="search">Filter tasks</label>
<input
id="search"
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
/>
<button type="button" onClick={onSort}>
Sort by title
</button>
<p aria-live="polite">
{visible.length === 0 ? 'No matching tasks' : `${visible.length} tasks`}
</p>
<ul>
{visible.map(t => (
<li key={t.id}>
<input
type="checkbox"
id={`task-${t.id}`}
checked={t.completed}
onChange={() => onToggle(t.id)}
/>
<label htmlFor={`task-${t.id}`}>Mark complete</label>
<Link to={`/tasks/${t.id}`}>{t.title}</Link>
</li>
))}
</ul>
</div>
);
}
function TaskDetail({ tasks, onToggle }) {
const { id } = useParams();
const task = tasks.find(t => t.id === Number(id));
if (!task) {
return (
<div>
<p>Task not found</p>
<Link to="/tasks">Back to list</Link>
</div>
);
}
return (
<div>
<h1>{task.title}</h1>
<label>
<input
type="checkbox"
checked={task.completed}
onChange={() => onToggle(task.id)}
/>
Completed
</label>
<Link to="/tasks">Back to list</Link>
</div>
);
}
Common Mistakes
- Using array index as
keyprop, which breaks state after reordering. - Forgetting to wrap
localStoragecalls intry/catch. - Comparing
useParams()values as numbers without parsing. - Mutating nested properties like
t.completed = !t.completedinstead of spreading. - Adding
role="button"to semantic<button>elements unnecessarily.
Follow-up Questions
How would you handle thousands of tasks?
- Virtualize the list with
react-windowto render only visible rows. - Memoize list items with
React.memoand stabilize callbacks withuseCallback. - Debounce the search input or use
useDeferredValue. - Move to IndexedDB for larger datasets since
localStoragehas size limits and synchronous I/O.
What if localStorage writes become a performance bottleneck?
- Debounce writes so rapid changes batch into fewer serialization calls.
- Consider storing only deltas or using a state management library with middleware for throttled persistence.