Summary - Advanced custom hooks
- React course
- Intermediate
- Lesson 8/80
- 5 min
Combine useFetch with useDebounce to write a search box.
Summary - Advanced custom hooks
In this group we wrote three powerful custom hooks: useLocalStorage for persistent state, useFetch for data fetching, and useDebounce for slowing changes. All three are daily tools in real projects.
The common principle: hooks combine state and effect, pull complex logic out of components, and form testable, reusable pieces. Composable structures can be built by nesting hooks.
In the next step you'll write a data page with useFetch; you'll handle loading and error states.
Practice DataPage with useFetch
Complete the skeleton. Write a DataPage component. Call useFetch("https://api.example.com/items"); destructure as [data, loading, error]. If loading, show <p>Loading</p>; if error, show <p>Error</p>; otherwise <p>{ '{ data.length }' } items</p>. Export it.
Starter code
// Write the DataPage component hereSample solution
function DataPage() {
const [data, loading, error] = useFetch("https://api.example.com/items");
if (loading) return <p>Loading</p>;
if (error) return <p>Error</p>;
return <p>{data.length} items</p>;
}
export default DataPage;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which hook is ideal for a search box?
- useDebounce Correct answer
- usePrevious
- useToggle
- useCounter
Explanation: useDebounce is ideal for search boxes.
2 Match the three hooks
| Term | Meaning |
|---|---|
useLocalStorage |
Persistent |
useFetch |
Data |
useDebounce |
Delay |
useEffect |
Side effect |