Skip to content

Hooks for Searching and Loading

The Course
•
20 min study

Loading data is a real job for an effect: the server is outside React. It's also fiddly: loading and error states, the ignore flag for stale answers from React Beginner Day 6, and not sending a request for every keystroke. Custom hooks keep all of that out of your components.

Search with two hooks React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so this waits like a real // request would. It logs each request so you can see how many are sent. const topics = [ "Components", "Props", "State", "Events", "Lists and keys", "Forms", "Effects", "Reducers", "Context", "Refs", "Custom hooks", "Transitions", ]; export async function searchTopics(query) { console.log(`request: "${query}"`); await new Promise((resolve) => setTimeout(resolve, 400)); const needle = query.trim().toLowerCase(); return topics.filter((topic) => topic.toLowerCase().includes(needle)); } import { useState } from "react"; import { useDebouncedValue } from "./hooks/useDebouncedValue.js"; import { useSearch } from "./hooks/useSearch.js"; export default function App() { const [query, setQuery] = useState(""); const debouncedQuery = useDebouncedValue(query, 300); const { results, loading, error } = useSearch(debouncedQuery); return ( <main> <h1>Find a topic</h1> <div className="toolbar"> <input aria-label="Search topics" placeholder="Search topics" value={query} onChange={(e) => setQuery(e.target.value)} /> {loading && <span className="muted">Searching…</span>} </div> {error && <p className="error">{error}</p>} <ul className="cards"> {results.map((topic) => ( <li key={topic} className="card">{topic}</li> ))} </ul> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } import { useEffect, useState } from "react"; // Returns value, but only after it has stopped changing for `delay` ms. export function useDebouncedValue(value, delay) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]); return debounced; } import { useEffect, useState } from "react"; import { searchTopics } from "../api.js"; export function useSearch(query) { const [results, setResults] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { let ignore = false; setLoading(true); setError(null); searchTopics(query) .then((data) => { if (!ignore) setResults(data); }) .catch((err) => { if (!ignore) setError(err.message); }) .finally(() => { if (!ignore) setLoading(false); }); return () => { ignore = true; }; }, [query]); return { results, loading, error }; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

App is short. It holds what the user typed, and asks two hooks for the rest:

JavaScript
const debouncedQuery = useDebouncedValue(query, 300);
const { results, loading, error } = useSearch(debouncedQuery);

useDebouncedValue

JavaScript
useEffect(() => {
  const id = setTimeout(() => setDebounced(value), delay);
  return () => clearTimeout(id);
}, [value, delay]);

Each new value starts a timer. If another arrives before it fires, the cleanup cancels the old timer. So the debounced value only changes once the user has paused for delay milliseconds.

Predict: how many requests?

api.js logs each request. Clear the console, then type hooks quickly. How many request lines appear?

Check your prediction

One: request: "hooks". Each keystroke restarted the 300 ms timer, so only the final value reached useSearch. Without the debounce, there'd be five requests, one per letter, and four of them wasted.

useSearch

The hook is the same load-in-an-effect pattern as React Beginner Day 6, with ignore set in the cleanup. It returns everything a caller needs as one object. Any component that needs topic search can now call useSearch(query), and a fix to the loading logic fixes all of them:

JavaScript
export function useSearch(query) {
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    let ignore = false;
    setLoading(true);
    setError(null);
    searchTopics(query)
      .then((data) => {
        if (!ignore) setResults(data);
      })
      .catch((err) => {
        if (!ignore) setError(err.message);
      })
      .finally(() => {
        if (!ignore) setLoading(false);
      });
    return () => {
      ignore = true;
    };
  }, [query]);

  return { results, loading, error };
}

Hooks can use hooks

useSearch calls useState and useEffect. A hook can also call your own hooks. You could combine the two into one useTopicSearch(query) that debounces internally. Whether to split or combine is a design choice: separate hooks are easier to reuse; one hook is simpler to call.

Exercise

Show the count

Under the search box, show 12 topics with the number of results, and No topics match when there are none. Change only App.jsx.

Your working space React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so this waits like a real // request would. It logs each request so you can see how many are sent. const topics = [ "Components", "Props", "State", "Events", "Lists and keys", "Forms", "Effects", "Reducers", "Context", "Refs", "Custom hooks", "Transitions", ]; export async function searchTopics(query) { console.log(`request: "${query}"`); await new Promise((resolve) => setTimeout(resolve, 400)); const needle = query.trim().toLowerCase(); return topics.filter((topic) => topic.toLowerCase().includes(needle)); } import { useState } from "react"; import { useDebouncedValue } from "./hooks/useDebouncedValue.js"; import { useSearch } from "./hooks/useSearch.js"; export default function App() { const [query, setQuery] = useState(""); const debouncedQuery = useDebouncedValue(query, 300); const { results, loading, error } = useSearch(debouncedQuery); return ( <main> <h1>Find a topic</h1> <div className="toolbar"> <input aria-label="Search topics" placeholder="Search topics" value={query} onChange={(e) => setQuery(e.target.value)} /> {loading && <span className="muted">Searching…</span>} </div> {error && <p className="error">{error}</p>} <ul className="cards"> {results.map((topic) => ( <li key={topic} className="card">{topic}</li> ))} </ul> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } import { useEffect, useState } from "react"; // Returns value, but only after it has stopped changing for `delay` ms. export function useDebouncedValue(value, delay) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]); return debounced; } import { useEffect, useState } from "react"; import { searchTopics } from "../api.js"; export function useSearch(query) { const [results, setResults] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { let ignore = false; setLoading(true); setError(null); searchTopics(query) .then((data) => { if (!ignore) setResults(data); }) .catch((err) => { if (!ignore) setError(err.message); }) .finally(() => { if (!ignore) setLoading(false); }); return () => { ignore = true; }; }, [query]); return { results, loading, error }; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

A results count and an empty message both follow from the returned array. Neither needs its own state.

Hint 2: a first step

results.length is a derived value: no new state, no effect.

Show one solution
JSX
<p className="muted">
  {results.length === 0 ? "No topics match" : `${results.length} topics`}
</p>

Was this article helpful?

Your response is saved on this device.