Fetching data from APIs is a fundamental part of building React applications. Whether you want to display user info, fetch posts, or get weather data, React offers simple ways to interact with external APIs and handle asynchronous data.
Most modern apps are dynamic β they rely on external data. React components often need to fetch data asynchronously, update the UI once data arrives, and handle loading or error states gracefully.
fetch()
in React
The JavaScript fetch()
API is commonly used to request data. Hereβs how you fetch data inside a React functional component using the useEffect
hook:
import React, { useState, useEffect } from 'react'; function UsersList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/users') .then(response => { if (!response.ok) throw new Error('Network error'); return response.json(); }) .then(data => { setUsers(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); if (loading) return <p style={{color: '#1e90ff', fontWeight: '600'}}>Loading users...</p>; if (error) return <p style={{color: 'red', fontWeight: '600'}}>Error: {error}</p>; return ( <ul style={{ listStyle: 'none', paddingLeft: 0 }}> {users.map(user => ( <li key={user.id} style={{ marginBottom: '10px', padding: '8px', background: '#e1f5fe', borderRadius: '6px' }}> <strong>{user.name}</strong> β {user.email} </li> ))} </ul> ); }
users
data, loading
state, and error
message.
[]
).
Async/await syntax helps write asynchronous code more readably. Hereβs the same fetch example rewritten with async/await:
import React, { useState, useEffect } from 'react'; function UsersList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function fetchUsers() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); setUsers(data); } catch (err) { setError(err.message); } finally { setLoading(false); } } fetchUsers(); }, []); if (loading) return <p style={{color: '#1e90ff', fontWeight: '600'}}>Loading users...</p>; if (error) return <p style={{color: 'red', fontWeight: '600'}}>Error: {error}</p>; return ( <ul style={{ listStyle: 'none', paddingLeft: 0 }}> {users.map(user => ( <li key={user.id} style={{ marginBottom: '10px', padding: '8px', background: '#e1f5fe', borderRadius: '6px' }}> <strong>{user.name}</strong> β {user.email} </li> ))} </ul> ); }
React Query
or Redux Toolkit Query
for advanced data fetching & caching.Axios is a popular third-party library that simplifies HTTP requests and supports features like interceptors and automatic JSON parsing.
import React, { useState, useEffect } from 'react'; import axios from 'axios'; function UsersList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/users') .then(response => { setUsers(response.data); setLoading(false); }) .catch(error => { setError(error.message); setLoading(false); }); }, []); if (loading) returnLoading users...
; if (error) returnError: {error}
; return (
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!