Fetching Data
To load data from an API in a client component, fetch it inside useEffect and store the result in state. Track loading and error states so the user always sees something useful.
function Users() {
const [users, setUsers] = useState<{ id: number; name: string }[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState("")
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => setUsers(data))
.catch(() => setError("Failed to load"))
.finally(() => setLoading(false))
}, [])
if (loading) return <p>Loading...</p>
if (error) return <p>{error}</p>
return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
}