Effects and loading data
useEffect, fetching from an API, and handling loading and errors.
useEffect runs code after the page has been drawn. Use it to connect to things outside React, such as a server.
React (JSX)
import { useEffect, useState } from "react";
export default function Jobs() {
const [jobs, setJobs] = useState(null);
const [error, setError] = useState("");
useEffect(() => {
let cancelled = false;
fetch("/api/jobs")
.then((r) => (r.ok ? r.json() : Promise.reject(new Error("Could not load"))))
.then((data) => { if (!cancelled) setJobs(data); })
.catch((e) => { if (!cancelled) setError(e.message); });
return () => { cancelled = true; };
}, []);
if (error) return <p>{error}</p>;
if (!jobs) return <p>Loading…</p>;
return <ul>{jobs.map((j) => <li key={j.id}>{j.title}</li>)}</ul>;
}- The array at the end lists what the effect depends on. An empty array means it runs once.
- The returned function is the clean-up, which runs when the component goes away.
- Do not use an effect to calculate something you can work out during render.