React · Lesson 54 of 120
useFetch
A data hook.
Fetching data needed three pieces of state, an effect, and an ignore flag. That's a lot to repeat. Let's wrap it in a hook.
- Lots to repeat
- Wrap it
- useFetch
A data hook
Use fetch wraps everything from the fetching lesson. It tracks the data, loading, and error, and ignores stale results. Now any component can load data in one line. Here we load the products, and show the gear. Run it.
App.jsxjsx
import { useState, useEffect } from "react";
import { getProducts } from "./api";
function useFetch(load) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
let ignore = false;
load()
.then(data => !ignore && setState({ data, loading: false, error: null }))
.catch(err => !ignore && setState({ data: null, loading: false, error: err.message }));
return () => { ignore = true; };
}, [load]);
return state;
}
export default function App() {
const { data, loading, error } = useFetch(getProducts);
if (loading) return <p>Loading...</p>;
if (error) return <small>{error}</small>;
return <ul>{data.filter(p => p.type === "gear").map(p => <li key={p.id}>{p.name} — £{p.price}</li>)}</ul>;
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses api.js
const PRODUCTS = [
{ id: 1, name: "Trail 500", price: 849.5, type: "bike", stock: 12 },
{ id: 2, name: "City 200", price: 450, type: "bike", stock: 0 },
{ id: 3, name: "Volt 7", price: 2199, type: "bike", stock: 4 },
{ id: 4, name: "Helmet", price: 40, type: "gear", stock: 30 },
{ id: 5, name: "Lights", price: 25, type: "gear", stock: 18 },
];
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
export async function getProducts() {
await wait(300);
return PRODUCTS;
}
export async function getProduct(id) {
await wait(300);
const product = PRODUCTS.find(p => p.id === Number(id));
if (!product) throw new Error(`Product ${id} not found`);
return product;
}Also uses actions.json
[{"wait": 600}]Summary
Use fetch turns loading, errors, and race handling into one line. Next, a new section on performance, starting with use memo.
Key takeaways- useFetch(load)
- data, loading, error
- One line
Next up: useMemo — skip slow work