Performance: Loading states for data
This concept affects how quickly users see feedback during data fetching, impacting perceived load speed and interaction responsiveness.
Jump into concepts and practice - no test required
import { useState, useEffect } from 'react'; export default function Page() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(json => { setData(json); setLoading(false); }); }, []); if (loading) return <div role="status" aria-live="polite">Loading data...</div>; return <Content data={data} />; }
export default async function Page() { const data = await fetch('/api/data').then(res => res.json()); return <div>{data ? <Content data={data} /> : null}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No loading state | Minimal DOM nodes | 0 reflows until data arrives | Single paint delayed | [X] Bad |
| Simple loading text | Few DOM nodes | 1 reflow on loading display | Light paint cost | [OK] Good |
import { useState, useEffect } from 'react';
export default function DataLoader() {
const [loading, setLoading] = useState(true);
const [data, setData] = useState(null);
useEffect(() => {
setTimeout(() => {
setData('Hello World');
setLoading(false);
}, 1000);
}, []);
if (loading) return <div>Loading...</div>;
return <div>{data}</div>;
}import { useState, useEffect } from 'react';
export default function Fetcher() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
useEffect(() => {
setLoading(true);
fetch('/api/data')
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
return <div>{JSON.stringify(data)}</div>;
}