screen size not supported

React JSON API examples (useEffect, SWR, React Query)

Last updated 2026-05-20

When to use this

Use this when you are wiring a JSON API into a React UI. The three patterns below — vanilla useEffect, SWR, React Query — give you progressively more caching, dedupe, and refetch logic for free.

Example JSON

Reference JSON payload returned by /users/1 (used in every snippet below).
{
  "id": 1,
  "firstName": "Emily",
  "lastName": "Johnson",
  "email": "emily.johnson@x.example",
  "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.

// click the button to populate this block

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}"
}