Loading & UI States
The data/loading/error state pattern, skeleton screens, and optimistic updates
Skills taught: api.loading-state-pattern, api.skeleton-ui, api.optimistic-update, api.abort-on-unmount
The three-state fetch pattern
// ── The three-state pattern (vanilla JS) ──
const state = { data: null, loading: false, error: null };
async function fetchUser(id) {
state.loading = true;
state.error = null;
render(); // show spinner
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
state.data = await res.json();
state.loading = false;
} catch (err) {
state.error = err.message;
state.loading = false;
}
render(); // update UI
}
function render() {
if (state.loading) return showSpinner();
if (state.error) return showError(state.error);
if (state.data) return showUser(state.data);
/* nothing loaded yet */return showEmpty();
}
// ── React hook version ──
function useUser(id) {
const [state, setState] = React.useState({ data: null, loading: true, error: null });
React.useEffect(() => {
if (!id) return;
const controller = new AbortController();
setState(s => ({ ...s, loading: true, error: null }));
fetch(`/api/users/${id}`, { signal: controller.signal })
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(data => setState({ data, loading: false, error: null }))
.catch(err => {
if (err.name === 'AbortError') return; // component unmounted — ignore
setState({ data: null, loading: false, error: err.message });
});
return () => controller.abort(); // cleanup: cancel on unmount or id change
}, [id]);
return state;
}
// Usage:
function UserProfile({ userId }) {
const { data: user, loading, error } = useUser(userId);
if (loading) return <Skeleton />;
if (error) return <ErrorMessage message={error} />;
return <div>{user.name}</div>;
}
// ── Optimistic update ──
async function toggleLike(postId, isLiked) {
// Update UI immediately — don't wait for server
setPosts(posts => posts.map(p =>
p.id === postId ? { ...p, liked: !isLiked, likes: p.likes + (isLiked ? -1 : 1) } : p
));
try {
await fetch(`/api/posts/${postId}/like`, {
method: isLiked ? 'DELETE' : 'POST',
});
} catch (err) {
// Revert the optimistic update
setPosts(posts => posts.map(p =>
p.id === postId ? { ...p, liked: isLiked, likes: p.likes + (isLiked ? 1 : -1) } : p
));
showToast('Failed to update like');
}
}
Frequently Asked Questions
Should I use React Query or write my own loading state logic?
For any real application, use React Query (TanStack Query) or SWR. They handle: caching (no duplicate requests for the same data), background refetching, stale-while-revalidate, retry logic, pagination, optimistic updates, and the three-state pattern — all out of the box. Writing it manually works for learning but doesn't scale. React Query's core bundle is ~12kb gzipped — a worthwhile investment for every app that talks to an API.