Skip to content
DevFlash
Back to the challenge

Commented solution

Filterable list with empty states

Why it works

  • The filtered list is derived from props and the query on each render, so there is no second state to keep in sync.
  • Normalizing once (trim + lowercase) keeps every comparison consistent.
  • role="status" makes screen readers announce the new count without moving focus.
  • For thousands of items, useMemo around the filter would avoid recomputing on unrelated renders; here it is not needed.
/src/FilterableList.tsx
import { useState } from "react";
type Item = { id: string; name: string };
export function FilterableList({ items }: { items: Item[] }) {
const [query, setQuery] = useState("");
const needle = query.trim().toLowerCase();
const visible = needle === ""
? items
: items.filter((item) => item.name.toLowerCase().includes(needle));
if (items.length === 0) return <p>Nothing to show yet</p>;
return (
<div>
<label>
Filter <input value={query} onChange={(e) => setQuery(e.target.value)} />
</label>
<p role="status">{visible.length === 1 ? "1 result" : `${visible.length} results`}</p>
{visible.length === 0 ? (
<p>No matches for "{query.trim()}"</p>
) : (
<ul aria-label="Results">
{visible.map((item) => <li key={item.id}>{item.name}</li>)}
</ul>
)}
</div>
);
}

What a good explanation covers

  • Explains why the filtered list is not a separate state.
  • Distinguishes the two empty states and why each message exists.
  • Mentions when memoization would start to matter.

Sources