HomeInterview QuestionsCan you explain how to handle basic data fetching …

Can you explain how to handle basic data fetching in ReactJS?

🟡 Medium Conceptual Junior level
1Times asked
Apr 2026Last seen
Apr 2026First seen

💡 Model Answer

In ReactJS, data fetching is typically performed inside a component’s lifecycle using the useEffect hook. The pattern involves three main steps: 1) Declare state variables for the data, loading status, and any error using useState. 2) Inside useEffect, define an async function that calls the API (e.g., using fetch or axios). 3) Call the async function, update the state with the response, and handle errors. Example:

js
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  const fetchData = async () => {
    try {
      const res = await fetch('https://api.example.com/items');
      if (!res.ok) throw new Error('Network response was not ok');
      const json = await res.json();
      setData(json);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  fetchData();
}, []);

Render logic checks loading and error states before displaying data. This approach keeps the component declarative, ensures cleanup on unmount, and handles asynchronous operations cleanly. For larger apps, consider using libraries like React Query or SWR for caching, refetching, and global state management of server data.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500