R

React Handbook

Clean • Professional

React API Integration — Top Interview Questions & Answers

3 minute

React API Integration — Interview Questions & Answers

Ques 1: What is API Integration in React?

Ans: API Integration in React refers to connecting your app to external data sources — such as REST APIs, GraphQL APIs, or backend services — to fetch, display, and update data dynamically.

React handles this process using JavaScript fetch(), Axios, or data-fetching libraries like React Query and SWR.

Ques 2: What is the difference between Fetch API and Axios?

FeatureFetch APIAxios
Built-inNative in browsersRequires installation
SyntaxPromise-basedPromise-based but simpler
JSON HandlingMust use .json() manuallyAuto-converts response to JSON
Error HandlingLimited (only rejects on network error)Handles HTTP errors automatically
Request CancelManual via AbortControllerBuilt-in cancel token support

Example using Fetch:

fetch('<https://api.example.com/data>')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

Example using Axios:

import axios from 'axios';
axios.get('<https://api.example.com/data>')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

Ques 3: How do Promises work in React API calls?

Ans: Promises handle asynchronous operations, allowing code to run without blocking the UI.

A Promise returns:

  • Pending
  • Fulfilled
  • Rejected

Example:

fetch('<https://api.example.com/users>')
  .then(response => response.json())
  .then(data => console.log('Users:', data))
  .catch(error => console.error('Error:', error));

Ques 4: What is Async/Await in React API calls?

Ans: async/await makes asynchronous code look synchronous and is easier to read than .then() chains.

Example:

const getData = async () => {
  try {
    const response = await fetch('<https://api.example.com/users>');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

Ques 5: How do you use useEffect() for data fetching in React?

Ans: The useEffect Hook is used to perform side effects such as fetching data after a component mounts.

Example:

import React, { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('<https://api.example.com/users>')
      .then(res => res.json())
      .then(data => setUsers(data))
      .catch(err => console.error(err));
  }, []);

  return (
    <ul>
      {users.map(u => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

Ques 6: What is React Query and why is it used?

Ans: React Query simplifies data fetching, caching, and synchronization with APIs.

It automatically handles:

  • Background refetching
  • Data caching
  • Loading and error states

Example:

import { useQuery } from '@tanstack/react-query';

function Users() {
  const { data, error, isLoading } = useQuery(['users'], () =>
    fetch('<https://api.example.com/users>').then(res => res.json())
  );

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error!</p>;

  return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

Ques 7: What is SWR in React?

Ans: SWR (Stale-While-Revalidate) is a lightweight library from Vercel for data fetching with caching and revalidation. It automatically updates data in the background.

Example:

import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());

function Profile() {
  const { data, error } = useSWR('<https://api.example.com/profile>', fetcher);

  if (error) return <div>Error loading</div>;
  if (!data) return <div>Loading...</div>;
  return <div>Hello {data.name}</div>;
}

Ques 8: What is Pagination?

Ans: Pagination divides large data sets into smaller pages, improving performance and user experience.

Example:

function PaginatedList({ page }) {
  useEffect(() => {
    fetch(`https://api.example.com/users?page=${page}`)
      .then(res => res.json())
      .then(data => console.log(data));
  }, [page]);
}

Ques 9: What is Infinite Scroll in React?

Ans: Infinite scrolling loads new data as the user scrolls, similar to social media feeds.

Example:

  • Use IntersectionObserver or scroll position to trigger API calls.
  • Libraries like react-infinite-scroll-component simplify it.

Ques 10: How do you handle errors during API requests in React?

Ans: Common strategies:

  • Wrap fetch/axios in try...catch
  • Show fallback UI or toast message
  • Use custom error boundaries for global handling

Example:

try {
  const res = await fetch('/api/data');
  if (!res.ok) throw new Error('Network response was not ok');
} catch (err) {
  console.error('Fetch error:', err);
}

Ques 11: How can you implement Retry Logic in React?

Ans: Retry logic automatically re-attempts failed API calls.

Example with React Query:

useQuery(['data'], fetchData, { retry: 3 });

Ques 12: What are best practices for API Integration in React?

  • Use async/await for clarity
  • Handle errors gracefully
  • Cache results using React Query/SWR
  • Show loading and error states
  • Avoid API calls inside loops
  • Use environment variables for API keys

Article 0 of 0