Skip to main content

How to implement a loading indicator (Loader)?

1. A basic spinner driven by a loading flag

javascript
import { useEffect, useState } from "react"; export function Users() { const [data, setData] = useState<any[] | null>(null); const [loading, setLoading] = useState(true); const [err, setErr] = useState<Error | null>(null); useEffect(() => { (async () => { try { const res = await fetch("/api/users"); if (!res.ok) throw new Error(`HTTP ${res.status}`); setData(await res.json()); } catch (e: any) { setErr(e); } finally { setLoading(false); } })(); }, []); if (loading) return <Loader ariaLabel="Loading users…" />; if (err) return <p role="alert">Error: {err.message}</p>; return <ul>{data!.map(u => <li key={u.id}>{u.name}</li>)}</ul>; } function Loader({ ariaLabel = "Loading…" }: { ariaLabel?: string }) { return ( <div className="loader" role="status" aria-live="polite" aria-label={ariaLabel} /> ); }

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.