React JSON API examples (useEffect, SWR, React Query)
Last updated 2026-05-20
Example JSON
Reference JSON payload returned by /users/1 (used in every snippet below).
{
"id": 1,
"firstName": "Emily",
"lastName": "Johnson",
"email": "[email protected]",
"username": "emilys",
"image": "https://jsonexamples.com/image/200?text=User+1",
"address": {
"address": "626 Main Street",
"city": "Phoenix",
"state": "OK",
"postalCode": "29920",
"country": "United States"
}
}Request examples
import { useEffect, useState } from 'react';
function useUser(id) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let alive = true;
fetch('https://jsonexamples.com/users/' + id)
.then(r => r.ok ? r.json() : Promise.reject(r.status))
.then(d => { if (alive) setUser(d); })
.catch(err => alive && setError(err));
return () => { alive = false; };
}, [id]);
return { user, error };
}Try the live endpoint
Click below to call /users/1 from your browser.
GET
/users/1{
"hint": "Click 'Run' to call the live endpoint"
}Common variations
Optimistic update with SWR
{
"snippet": "import useSWR, { mutate } from 'swr';\n\nasync function toggleTodo(id, completed) {\n mutate('/todos/' + id, prev => ({ ...prev, completed }), false);\n await fetch('/todos/' + id, { method: 'PATCH', body: JSON.stringify({ completed }) });\n mutate('/todos/' + id);\n}"
}