Skip to content
ClapelloNotes by Barath
ReactCh 06 · 6/6
Core3 min readUpdated

React / 33

Search & filter: derive, don't copy

TL;DR

Keep the full list in state, keep what the user typed in state, and calculate the visible list on every render. No lost data, no copies to keep in sync.

Step 1 · A controlled input

To use what the user types, keep it in state and wire the input both ways:

const [query, setQuery] = useState("");
 
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search recipes" />

value={query} makes React the boss of the input: it always shows query. onChange updates query on every key press, which re-renders with the new value. This is called a controlled input.

Leave out onChange and you can't type: React keeps putting "" back. React warns about exactly this in the console.

Step 2 · Filter while rendering

RecipeSearch.jsx
import { useState } from "react";
 
export default function RecipeSearch({ recipes }) {
  const [query, setQuery] = useState("");
  const [topOnly, setTopOnly] = useState(false);
 
  const q = query.trim().toLowerCase();
  const visible = recipes.filter(
    (r) => r.name.toLowerCase().includes(q) && (!topOnly || r.rating >= 4.7),
  );
 
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search recipes" />
      <label>
        <input type="checkbox" checked={topOnly} onChange={(e) => setTopOnly(e.target.checked)} />
        Top rated only
      </label>
      <p>{visible.length} of {recipes.length} recipes</p>
      <ul>{visible.map((r) => <li key={r.id}>{r.name} · ★ {r.rating}</li>)}</ul>
    </>
  );
}

visible is a plain const, worked out fresh on every render from recipes, query and topOnly. Type a letter and it re-filters. Clear the box and everything is back, because recipes was never touched. The .toLowerCase() on both sides makes "PIZZA" match "Margherita Pizza", and .trim() ignores stray spaces.

state

recipes

30 items, never changed by search

state

query

"piz"
every render

derived · plain const

visible

recipes.filter(r => r.name.toLowerCase().includes(query.toLowerCase()))
map to JSX

screen

2 cards

Clear the box and all 30 come back
Store only what can't be worked out: the full list and what the user typed. The visible list is calculated fresh on every render.

This is derived state: anything you can calculate from props or state should be calculated, not stored.

Why not just update the list?

Search: overwrite vs derive

Try it

how the search works

state: list = 8 items

on screen = 8 items

  • Margherita Pizza
  • Pepperoni Pizza
  • Greek Salad
  • Caesar Salad
  • Chicken Biryani
  • Veg Biryani
  • Pad Thai
  • Dal Tadka
In 'overwrite' mode, search pizza, then search salad. The salads are gone for good. Switch to 'derive' and the full list is always there to search.

Don't

Overwrite the list

function handleSearch() {
  setRecipes(recipes.filter((r) => r.name.includes(query)));
}

The non-matches are deleted from state. Search "pizza", then "salad", and nothing is left to find.

Do

Derive the visible list

const visible = recipes.filter((r) =>
  r.name.toLowerCase().includes(query.trim().toLowerCase()),
);

recipes stays complete. The view is recalculated every render.

A common half-fix is two copies in state, allRecipes and filteredRecipes, and remembering to update both on every fetch, search and filter. It works until someone forgets one setFilteredRecipes call. Deriving means there is nothing to forget.

Is filtering every render slow?

No. Filtering a few hundred items takes well under a millisecond. Only for genuinely heavy work (thousands of items with expensive checks) reach for useMemo to cache the result between renders. Measure before you optimise.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.