Menu

Fetching Data with fetch()

Working with APIs

Fetching Data with fetch()

What is an API Call?

Most real applications get their data from a server rather than hard-coding it. An API call is a request your app sends to a server, which responds with data usually in JSON format.

Why is it Used?

A course list that lives in a JavaScript array cannot change without a code deployment. A course list fetched from an API updates the moment the server data changes.

Syntax

jsx

useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, []);

Example

src/components/UserList.jsx

jsx

import { useState, useEffect } from "react";
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
async function loadUsers() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
setUsers(data);
}
loadUsers();
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} — {user.email}
</li>
))}
</ul>
);
}
export default UserList;

How It Works

  • The fetch lives inside useEffect with [], so it runs once when the component appears.
  • async function loadUsers() is declared inside the effect and then called. The effect callback itself cannot be async — React expects it to return either nothing or a cleanup function, and an async function returns a Promise.
  • await response.json() parses the JSON body. This is a second await because reading the body is itself asynchronous.
  • setUsers(data) puts the result into state, which re-renders the list.
  • useState([]) starts as an empty array, so the first render's .map() works instead of crashing on undefined.

jsonplaceholder.typicode.com is a free public API for practice. Use it freely while learning.

Output

A list of ten users with names and email addresses, appearing a moment after the page loads.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details