javascript / beginner
Snippet
Fetching Asynchronous API Data on Component Mount
Asynchronous operations such as HTTP requests should be triggered inside the useEffect hook. Declaring an async function inside the effect allows awaiting network responses safely and storing the result in local state.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { useState, useEffect } from 'react';function UserProfile({ userId }) {const [user, setUser] = useState(null);useEffect(() => {async function loadData() {const response = await fetch(`https://api.example.com/users/${userId}`);const data = await response.json();setUser(data);}loadData();}, [userId]);return <div>{user ? user.name : 'Loading profile...'}</div>;}
react
Breakdown
1
const [user, setUser] = useState(null);
Initializes a state variable to hold the fetched user record, starting as null.
2
useEffect(() => {
Executes side effects when the component mounts or when listed dependencies change.
3
async function loadData() {
Defines an inner asynchronous function to handle the Promise-based API request.
4
}, [userId]);
Dependency array that ensures data re-fetches whenever userId changes.