# SWR

Goal: SWR in a React page, with its first data coming from the page's `load` and its cache refreshed after a change. The runnable sample is `examples/data-react/`; `swr` is a devDependency of that example, and Hamur has no module for it.

When Hamur's own data is enough: `useAsyncData(handler, input)` reads, `useAction` or `Form` changes and refreshes the page, and `router.refresh(key)` re-runs what depends on a key ([Data](/data)). Reach for SWR when you want its cache by key across components, revalidation on focus and reconnect per key, or its small API on top of an existing fetcher. A handler is the function both call.

1. Give SWR a cache for each request. Its default cache is a module-level `Map`, which every request on the server would share. `SWRConfig` with `provider: () => new Map()` makes a fresh one when it mounts, so put it in the root component (`app/app.tsx`, [Root component](/api-reference/routing-details#root-component)):

````tsx [examples/data-react/app/app.tsx]
import { useState } from "react"
import { Outlet } from "@hamur/adapter-react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { SWRConfig } from "swr"

export default function App() {
  const [queryClient] = useState(() => new QueryClient())
  return (
    <QueryClientProvider client={queryClient}>
      <SWRConfig value={{ provider: () => new Map() }}>
        <Outlet />
      </SWRConfig>
    </QueryClientProvider>
  )
}
````

2. Seed the hook from the page's `load`. The `load` calls the handler, so the server render and the first browser render have the data, and it is in the page payload ([What goes into the payload](/data#what-goes-into-the-payload)). SWR does not fetch while the server renders, so give `useSWR` the data as `fallbackData`. With `revalidateIfStale: false` it does not fetch again when the page mounts either:

````ts [examples/data-react/app/pages/swr.load.ts]
import type { Load } from "hamur/app"
import { listTodos } from "#server"

export const load = (async () => ({ todos: await listTodos() })) satisfies Load
````

````tsx [examples/data-react/app/pages/swr.tsx]
import { useState } from "react"
import { useData } from "@hamur/adapter-react"
import useSWR from "swr"
import type { Todo } from "../../shared/todo.ts"
import { addTodo, listTodos } from "#server"

export default function Todos() {
  const { todos: seed } = useData<{ todos: Todo[] }>()
  const [title, setTitle] = useState("")
  const { data, mutate } = useSWR("todos", () => listTodos(), { fallbackData: seed, revalidateIfStale: false })

  return (
    <main>
      <h1>SWR</h1>
      <ul>
        {data?.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
      <form
        onSubmit={async (event) => {
          event.preventDefault()
          await addTodo({ title })
          setTitle("")
          await mutate()
        }}
      >
        <input value={title} onChange={(event) => setTitle(event.target.value)} />
        <button>Add</button>
      </form>
    </main>
  )
}
````

The fetcher is the handler. In the browser a call is a request; the key `"todos"` is only the name of the cache entry.

3. Refresh after a change. The page calls the handler and then `mutate()`, the bound function `useSWR` returns, which revalidates the key. A handler called this way does not go through `useAction`, so Hamur does not read the page again; the SWR cache is the one you refresh. For one key across the app, `useSWRConfig().mutate(key)` does the same.

4. Know which copy wins. `fallbackData` is used while the key has no data in the cache. After the first fetch or a `mutate()`, the cache has the data and a later `load` does not replace it. Navigating away and back keeps the entry, and `revalidateIfStale: false` keeps it without a request until you call `mutate()` or set a `refreshInterval`.

See also: [Data](/data), [Handlers](/handlers), [TanStack Query](/recipes/tanstack-query), [Hydration](/recipes/hydration).
