LearnFrenzy
Sign in Take a free test

React interview · Set 4 of 8

Routing, Data Fetching and Forms in React

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Navigation, data and input done right

Interviewers check for loading, error and empty states, race-condition handling, caching and validation — the details that make an app feel solid.

  • RoutingNested routes, params, guards and lazy loading.
  • DataEffects, TanStack Query and Suspense.
  • FormsValidation, actions and optimistic UI.

Real React apps load data, navigate between pages and submit forms. Interviewers check that you avoid the classic bugs — race conditions, missing loading and error states, refetching on every render — and know the tools teams actually use.

1. How do you set up routing with React Router?

Define routes, nest layouts with <Outlet />, read params with useParams and navigate with <Link> or useNavigate. Lazy-load route components to keep the first bundle small.

const router = createBrowserRouter([
  {
    path: '/', element: <AppLayout />, errorElement: <ErrorPage />,
    children: [
      { index: true, element: <Home /> },
      { path: 'courses/:slug', element: <CoursePage /> },
      { path: 'admin', lazy: () => import('./admin/route') },
    ],
  },
]);

function CoursePage() {
  const { slug } = useParams();
  return <h1>{slug}</h1>;
}

2. How do you protect routes that need login?

Wrap protected routes in a component that checks auth and redirects to the login page, remembering where the user wanted to go. The server must still check permissions — client-side guards only improve UX.

function RequireAuth({ children }) {
  const { user } = useAuth();
  const location = useLocation();
  if (!user) return <Navigate to="/login" state={{ from: location }} replace />;
  return children;
}

3. What is wrong with fetching data in useEffect naively?

Common bugs: no loading or error state, race conditions when inputs change quickly (an old response arrives last), no caching (every visit refetches), duplicate requests across components, and no retry. If you fetch in an effect, abort stale requests and track loading and errors.

useEffect(() => {
  const controller = new AbortController();
  setStatus('loading');
  fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
    .then(r => (r.ok ? r.json() : Promise.reject(new Error(r.status))))
    .then(data => { setResults(data); setStatus('done'); })
    .catch(err => { if (err.name !== 'AbortError') setStatus('error'); });
  return () => controller.abort();     // stale request cancelled
}, [query]);

4. Why use TanStack Query (React Query)?

It treats server data as a cache: deduplicates requests, caches by key, refetches in the background when stale, retries failures, handles pagination and gives you loading and error states — plus mutations with cache invalidation. Most of the hand-written effect code disappears.

function Orders() {
  const { data, isPending, error } = useQuery({
    queryKey: ['orders', page],
    queryFn: () => api(`/api/orders?page=${page}`),
    staleTime: 60_000,
  });
  const qc = useQueryClient();
  const cancel = useMutation({
    mutationFn: id => api(`/api/orders/${id}/cancel`, { method: 'POST' }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['orders'] }),
  });
  if (isPending) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;
  return <OrderTable orders={data} onCancel={id => cancel.mutate(id)} />;
}

5. How does Suspense work for loading states?

<Suspense fallback> shows a fallback while something inside is not ready — a lazy-loaded component or data from a Suspense-enabled source (React 19's use(), framework loaders, Suspense queries). It lets you declare loading UI at the right level instead of in every component.

<Suspense fallback={<DashboardSkeleton />}>
  <SalesChart />          {/* suspends until its data or code is ready */}
  <RecentOrders />
</Suspense>

6. How do you handle forms and validation at scale?

For simple forms, controlled inputs or the native FormData. For larger forms, React Hook Form with a schema validator (Zod) keeps re-renders low and validation declarative — and the same schema can validate on the server. In React 19, form actions with useActionState handle submission state.

const schema = z.object({
  name: z.string().min(2, 'Enter your name'),
  email: z.string().email('Enter a valid email'),
});

function SignupForm() {
  const { register, handleSubmit, formState: { errors, isSubmitting } } =
    useForm({ resolver: zodResolver(schema) });
  return (
    <form onSubmit={handleSubmit(signup)}>
      <input {...register('name')} />{errors.name && <p>{errors.name.message}</p>}
      <input {...register('email')} />{errors.email && <p>{errors.email.message}</p>}
      <button disabled={isSubmitting}>Create account</button>
    </form>
  );
}

7. How do you implement optimistic updates?

Update the UI immediately as if the request succeeded, then roll back if it fails. TanStack Query supports it in mutation callbacks; React 19 offers useOptimistic for form actions. Use it for low-risk actions such as likes or ticking a task.


8. How do you keep filters and pagination in the URL?

Read and write them with useSearchParams. The page becomes shareable and bookmarkable, the back button works, and refreshing keeps the user's place.

const [params, setParams] = useSearchParams();
const page = Number(params.get('page') ?? 1);
const city = params.get('city') ?? 'all';

function changeCity(next) {
  setParams(prev => { prev.set('city', next); prev.set('page', '1'); return prev; });
}

Remember

Key points

  • Abort stale requests

    Prevents out-of-order results.

  • Server state is a cache

    Use a query library.

  • URL holds view state

    Filters, page and tabs.

  • Validate with a schema

    Share it with the server.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the difference between staleTime and gcTime in TanStack Query? Intermediate

    staleTime is how long data counts as fresh (no refetch); gcTime is how long unused cached data is kept in memory before removal.

  2. 2 How do you handle a 401 from any API call? Intermediate

    Centralise it in the API client: try a token refresh once, otherwise clear the session and redirect to login.

  3. 3 How do you implement infinite scrolling with React? Intermediate

    useInfiniteQuery with a cursor plus an IntersectionObserver on a sentinel element that calls fetchNextPage.

  4. 4 Controlled or uncontrolled forms — which performs better? Intermediate

    Uncontrolled inputs (read on submit, as React Hook Form does) avoid a re-render per keystroke; controlled inputs are simpler when the UI reacts to every change.

  5. 5 What is a loader in React Router? Advanced

    A function attached to a route that fetches data before the route renders, so navigation and data loading start together; the component reads it with useLoaderData.

  6. 6 How do you debounce a search input in React? Basic

    Keep the input value in state and derive a debounced value with a small useDebounce hook (an effect with setTimeout and cleanup), or use useDeferredValue.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links