How do you handle loading, error and empty states when a screen fetches data from an API?
What the interviewer wants to hear
- Model the request as explicit states: loading, success, empty and error
- Use skeletons that match the layout to avoid layout shift, not just spinners
- Show helpful error messages with a retry, and check response.ok
- Handle race conditions and cancel stale requests with AbortController
- Use a server-cache library such as TanStack Query or SWR for caching, retries and deduplication
Model answer
I treat every request as having at least four states: loading, success with data, success but empty, and error. Modelling them explicitly, for example with a status field or a discriminated union in TypeScript, prevents impossible combinations like showing data and an error together. For loading I prefer skeletons shaped like the final content, which feel faster and avoid layout shift, and I avoid flashing a spinner for very fast responses. Empty states explain what is missing and offer an action, like "Create your first project". For errors, I check response.ok, show a clear message in plain language, offer a retry, and log details to monitoring. I also handle races: if the user changes filters quickly, I abort older requests with AbortController or ignore stale responses. In real projects I usually use TanStack Query or SWR, which provide caching, retries, deduplication and background refetching, so components stay simple.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Frontend Developer questions
- Explain the JavaScript event loop, including microtasks and macrotasks.
- How do you decide where to keep state in a React app: local state, context, a store, or a server-cache library?
- A page has a poor LCP score. How would you investigate and fix it?
- What testing strategy would you use for a frontend application?
- Explain client-side rendering, server-side rendering and static site generation. When would you use each?
- What happens between typing a URL in the browser and seeing the page rendered? Focus on the frontend side.
- A React screen feels slow. How do you find and reduce unnecessary re-renders?
- How do you use TypeScript effectively in a React codebase?
- How would you handle user authentication and tokens in a single-page app or Next.js frontend?