javascript / beginner
Snippet
Loading Remote API Data Asynchronously in useEffect
React components handle asynchronous operations such as HTTP network requests inside the useEffect hook. By declaring an async function inside the effect and calling it, you can fetch remote JSON data without blocking the component render cycle.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { useState, useEffect } from 'react';export function UserProfile() {const [user, setUser] = useState(null);useEffect(() => {async function loadUserData() {const response = await fetch('https://api.example.com/user');const data = await response.json();setUser(data);}loadUserData();}, []);if (!user) return <p>Loading...</p>;return <h2>{user.name}</h2>;}
react
Breakdown
1
useEffect(() => {
Registers a side effect that executes after the component mounts to the screen.
2
async function loadUserData() {
Defines an inner asynchronous function to safely perform promise-based operations.
3
const data = await response.json();
Waits for the network response to resolve and parses the body as a JavaScript object.
4
}, []);
Passes an empty dependency array to ensure the asynchronous fetch runs only once on mount.